什么叫DependancyProperty
来源:互联网 发布:淘宝刷流量怎么刷 编辑:程序博客网 时间:2024/05/01 09:40
DependencyProperty是Wpf属性定义中很重要的一个类,在传统的属性定义中,如一个控件的某属性变化了,需要重画才可以使属性的变化添加到控件。也就是说,你需要使用Graphics的实例来进行重画。而这样,是比较麻烦的事情。Wpf使用了DependencyProperty后,可以通过DependencyProperty的属性来指定是否将变化影响到界面或其子控件。有了这个机制,就可以大大加快了开发的速度。
源代码
下面自定义一个Button控件,它继承自Button类,并增加了属性BTNImage,而BTNImage又是使用DependencyProperty类型的ImageProperty设置的。基本上可以理解BTNImage才是你想要的东西,而set ,get访问器调用了DependencyProperty类型的对象,从而获取对象。FrameworkPropertyMetadata是一个描述DependencyProperty的实体,也就是开篇时提交的使用DependencyProperty的好处,都是要通过MetaData来设置的。可以验证数据的准确性,设置属性的所有者和类型,绑定属性名称等等。
public class WpfDependencyPropertyButton:Button
{
/// <summary>
/// 设置DependencyProperty属性
/// </summary>
public static readonly DependencyProperty ImageProperty;
/// <summary>
/// 设置Image的访问器
/// </summary>
public Image BTNImage
{
set {
SetValue(ImageProperty, value);
}
get
{
return (Image)GetValue(ImageProperty);
}
}
static WpfDependencyPropertyButton()
{
//设置DependencyProperty的默认描述
FrameworkPropertyMetadata _metadata = new FrameworkPropertyMetadata();
//设置默认值勤
_metadata.DefaultValue = null;
//设置是否影响布局
_metadata.AffectsMeasure = true;
//设置是否影响到其子控件
_metadata.Inherits = true;
//设置属性变化时的处理方法
_metadata.PropertyChangedCallback += OnImagePropertyChanged;
ImageProperty = DependencyProperty.Register("BTNImage", typeof(Image), typeof(WpfDependencyPropertyButton), _metadata);
}
/// <summary>
/// 设置回调方法
/// </summary>
/// <param name="obj"></param>
/// <param name="args"></param>
static void OnImagePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
Button _button = obj as Button;
_button.Content = args.NewValue;
}
}
在Window中引用Button
public class WpfSimpleWindow : Window
{
[STAThread]
public static void Main()
{
Application _application = new Application();
_application.Run(new WpfSimpleWindow());
}
public WpfSimpleWindow()
{
//设置Window的长和宽
Width = 96 * 4;
Height = 96 * 4;
Uri _uri = new Uri("http://www.myfirm.cn/images/logo.jpg");
BitmapImage _bitmapImage = new BitmapImage(_uri);
Image _image = new Image();
_image.Source = _bitmapImage;
WpfDependencyPropertyButton _button = new WpfDependencyPropertyButton();
_button.BTNImage = _image;
_button.HorizontalAlignment = HorizontalAlignment.Center;
_button.VerticalAlignment = VerticalAlignment.Center;
Content = _button;
}
}
- 什么叫DependancyProperty
- 什么叫模式 什么叫框架
- 什么叫"工作流"?什么叫"信息流"?
- 解释什么叫老公?什么叫老婆?
- 什么叫断章取义,什么叫曲解
- 什么叫表达式?什么叫语句? ~
- 什么叫白领?
- 这叫什么
- 什么叫牛B
- 什么叫关键字密度?
- 什么叫可扩展性?
- 什么叫 执行力?
- 什么叫"修炼"
- 什么叫web services
- 什么叫ISO9000
- 什么叫ISO
- 什么叫单反相机
- 什么叫壮观!
- 解救西西弗斯- 模型驱动架构
- C#接口与抽象的区别
- 小鸟先飞
- 寒假二次开发机房收费系统与软件工程的认识
- uboot启动第二阶段
- 什么叫DependancyProperty
- 鸿基酒店应收应付报表生成系统
- 放弃也是一种快乐
- HTTP POST GET 本质区别详解
- ASP.NET 和 IIS 配置自定义扩展名网页
- xmlHTTP技术资料
- 新年2010
- 获取远程服务器数据(asp,adodb.stream,保存远程图片,XMLHTTP)
- 远程获取类Asp xmlHttp