用户控件和自定义控件的定义及区别

(一).用户控件和自定义控件概述  
       用户控件(UserControl):  扩展名为*.ascx,跟*.aspx在结构上相似,是指页面中  
加载的功能块,只是用户控件不能单独作为页面运行,必须嵌入到*.aspx页面或其它用  
户控件中使用.  
       自定义控件,跟HtmlControl或WebControl相似,编译后可以添加引用到工具栏里  
面,直接用鼠标拖动使用.  
 
(二).使用        
       在一个大系统中,有时候会只能几个*.aspx页面,其余的都是做成*.ascx页面,  
这样可以增强页面之间的藕合性,一个用户控件*.ascx都作为一个独立的功能块.  
       自定义控件是指编译后直接可以放到工具箱中用,就像TextBox,DataGrid一样  
在设计器中可以用鼠标拖动到页面上使用.  
       自定义服务器控件分为两种:    
               1.一种是用*.aspx代码和*.cs代码编译后生成DLL,再添加引用到工具箱使用.          
                   一般用于WebForm中.        
               2.另一种是只用*.cs实现,再编译生成DLL,添加到工具箱使用.  
                   一般用于WinForm中.  
       自定义控件生成步骤:  
             比如:    
               1.  将一个Button从设计器拖到页面中,  
                     对按钮大小,颜色或文本设置一个固定值,保存文件名为:  a.cs  
               2.  csc  /r:System.dll  /t:library/out:../../A.dll    a.cs  
               3.  右击工具箱空白处,弹出右击菜单后,选“添加移除项”,将刚生成的DLL  
                     添加到工具箱里面来,这样,就可以像一般的Button一样拖动使用了
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在WPF中,我们可以通过依赖属性(Dependency Property)来定义定义属性,并绑定到对应的控件上。 以下是一个示例,演示如何定义定义属性,并绑定到按钮(Button)上: 1. 定义依赖属性 ```csharp public static readonly DependencyProperty MyCustomProperty = DependencyProperty.Register( "MyCustom", typeof(string), typeof(MyUserControl), new PropertyMetadata(string.Empty)); public string MyCustom { get { return (string)GetValue(MyCustomProperty); } set { SetValue(MyCustomProperty, value); } } ``` 在上面的代码中,我们使用DependencyProperty.Register方法来定义一个名为MyCustom的依赖属性。该属性的类型为string,所属的控件类型为MyUserControl。我们还通过PropertyMetadata设置了该属性的默认值为string.Empty。最后,我们定义了一个公共属性MyCustom,用于获取或设置该依赖属性的值。 2. 为控件添加自定义属性 ```xml <UserControl x:Class="MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Button Content="Click Me" MyCustom="Hello World!" /> </Grid> </UserControl> ``` 在上面的代码中,我们为Button控件添加了MyCustom属性,并设置了该属性的值为"Hello World!"。 3. 绑定自定义属性 ```xml <UserControl x:Class="MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Button Content="Click Me" MyCustom="{Binding MyValue}" /> </Grid> </UserControl> ``` 在上面的代码中,我们使用了数据绑定来绑定MyCustom属性。我们将该属性绑定到一个名为MyValue的属性上,这个属性可以是控件的DataContext属性,也可以是控件的父级元素属性。当MyValue属性的值发生变化时,MyCustom属性也会自动更新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值