只读依赖项属性
什么时候用
只读依赖项属性类似于普通依赖项属性,但其结构不允许从控件外部设置其值。如果你有一个纯粹为消费者提供信息的属性,例如 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来自privateDependencyPropertyKey。- CLR 属性设置器是
protected或private而不是public。
请注意,setter 将 MyPropertyPropertyKey 而不是 MyPropertyProperty 传递给 SetValue 方法。因为属性是以只读方式定义的,所以在属性上使用 SetValue 的任何尝试都必须使用接收 DependencyPropertyKey 的重载; 否则,将会抛出一个 InvalidOperationException。