浅谈WPF依赖项属性 (2)

完整的代码如下:

// Dependency Property public static readonly DependencyProperty CurrentTimeProperty = DependencyProperty.Register( "CurrentTime", typeof(DateTime), typeof(MyClockControl), new FrameworkPropertyMetadata(DateTime.Now)); // .NET Property wrapper public DateTime CurrentTime { get { return (DateTime)GetValue(CurrentTimeProperty); } set { SetValue(CurrentTimeProperty, value); } } static bool validateValueCallback(object data) { //自定义验证 return true; }

自定义一个依赖项属性,需要挺多的套路,当然这些套路不需要你一个一个代码来敲,在Visual Studio可以输入propdp再点击两次tab键,就可以创建依赖项属性模板。 只需修改模板的属性名称和类型即可。

模板代码如下:

public int MyProperty { get { return (int)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0)); 2. 附加属性

附加属性也是一种依赖项属性。与其他依赖项属性不同的时,其他的依赖项属性是应用到被注册的类上,而附加属性则是应用到其他的类上。

比如:Canvas的类的Top和Left等为附加属性,其他的元素并没有该属性,只有Canvas类有,在使用Canvas.Top时,如果为每个元素都定义一个这样的依赖项属性,那么就会大量的重复性代码,且不可维护更改。如果只在Canvas类型上定义这个依赖项属性,其他的元素只继承使用该属性就好。附加属性就是这样。

附加属性的定义和依赖项属性的定义几乎一样。唯一不同的是注册是通过调用DependencyProperty.GegisterAttached()方法来实现,且属性包装器为静态方法。

如:

public static readonly DependencyProperty TopProperty = DependencyProperty.RegisterAttached("Top", typeof(double), typeof(Canvas), new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.Inherits)); public static void SetTop(UIElement element, double value) { element.SetValue(TopProperty, value); } public static double GetTop(UIElement element) { return (double)element.GetValue(TopProperty); }

至此就可以像使用普通的CLR属性一样使用WPF的依赖项属性。

如有不对,请多多指教!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zywxgp.html