几乎所有的WPF控件都大量使用依赖属性。依赖项属性允许使用许多仅标准CLR属性无法使用的WPF功能,包括但不限于对样式、动画、数据绑定、值继承和更改通知的支持。
TextBox.Text属性是需要标准依赖项属性的简单示例。在这里,如果Text是标准的CLR属性,则无法进行数据绑定。
<TextBox Text="{Binding FirstName}" />
依赖性属性可以仅在从派生的类定义DependencyObject,例如FrameworkElement,Control等
创建标准依赖项属性而无需记住语法的最快方法之一是通过键入propdp然后按来使用“ propdp”代码段Tab。将插入一个代码片段,然后可以对其进行修改以满足您的需求:
public class MyControl : Control { public int MyProperty { get { return (int)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // 使用DependencyProperty作为MyProperty的后备存储。 // 这样可以启用动画,样式,绑定等。 public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(MyControl), new PropertyMetadata(0)); }
您应该Tab对代码段的不同部分进行必要的更改,包括更新属性名称,属性类型,包含类类型和默认值。
这里有一些重要的约定/规则:
为依赖项属性创建一个CLR属性。此属性用于对象的代码隐藏或其他使用者。它应该调用GetValue,SetValue因此消费者不必这样做。
正确命名依赖项属性。该DependencyProperty字段应为public static readonly。它的名称应与CLR属性名称相对应,并以“属性”结尾,例如Text和TextProperty。
不要向CLR属性的设置器添加其他逻辑。依赖项属性系统(特别是XAML)不使用CLR属性。如果要在属性值更改时执行操作,则必须通过PropertyMetadata以下方式提供回调:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(MyControl), new PropertyMetadata(0, MyPropertyChangedHandler)); private static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs args) { // 根据需要在此处使用args.OldValue和args.NewValue。 // 发送者是其属性已更改的对象。 // 需要一些拆箱。 }
为了消除Mode=TwoWay在绑定中指定的需求(类似于的行为TextBox.Text),请更新要使用的代码,以FrameworkPropertyMetadata代替PropertyMetadata并指定适当的标志:
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(MyControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));