只讀依賴項屬性
什麼時候用
只讀依賴項屬性類似於普通依賴項屬性,但其結構不允許從控制元件外部設定其值。如果你有一個純粹為消費者提供資訊的屬性,例如 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。