只读的依赖项属性与普通的依赖项属性相似,但其结构不允许从控件外部设置其值。如果您拥有仅供消费者参考的属性,则此方法很好用,例如IsMouseOver或IsKeyboardFocusWithin。
与标准依赖项属性一样,只读依赖项属性必须在从派生的类上定义DependencyObject。
public class MyControl : Control
{
private static readonly DependencyPropertyKey MyPropertyPropertyKey =
DependencyProperty.RegisterReadOnly("MyProperty", typeof(int), typeof(MyControl),
new FrameworkPropertyMetadata(0));
public static readonly DependencyProperty MyPropertyProperty = MyPropertyPropertyKey.DependencyProperty;
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
private set { SetValue(MyPropertyPropertyKey, value); }
}
}适用于常规依赖项属性的约定也适用于此处,但有两个主要区别:
在DependencyProperty从源private DependencyPropertyKey。
在CLR的属性设置是protected或private不是public。
需要注意的是二传手传递MyPropertyPropertyKey,而不是MyPropertyProperty到SetValue方法。由于该属性是只读定义的,因此任何尝试SetValue对该属性使用的尝试都必须与具有receive的重载一起使用DependencyPropertyKey。否则,InvalidOperationException将抛出。