我正在讀關於如何做一個參數化的風格(here)的教程。在它中,它使用了一些依賴屬性。它宣稱它們的方式:你打算如何聲明一個依賴屬性?
public static Brush GetTickBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(TickBrushProperty);
}
public static void SetTickBrush(DependencyObject obj, Brush value)
{
obj.SetValue(TickBrushProperty, value);
}
public static readonly DependencyProperty TickBrushProperty =
DependencyProperty.RegisterAttached(
"TickBrush",
typeof(Brush),
typeof(ThemeProperties),
new FrameworkPropertyMetadata(Brushes.Black));
現在,因爲我喜歡的片段,我說幹就幹,找了一個,看我沒有做一個。有一個,但在一個完全不同的風格:
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));
現在,我不明白:什麼是這兩者之間的區別?爲什麼需要DependencyObject
才能獲得價值,而另一個則不需要?你在不同的場景中使用它們嗎?
他們除了他們使用的是不同的一樣。第一種方法使用靜態方法所以這將允許設置使用語法像控制值:Control.GetTickBrush([InstanceOfTheControl])。第二種方法可讓您通過實例對象訪問這些值。所以你必須做Control test = new control(); test.MyProperty獲取或設置值。 – user2453734
@ user2453734:他們*不*相同。請注意,有兩種不同的方法用於註冊它們。 –
良好的捕獲,一個用於控制,它有一個我屬性類型的屬性(第二個例子)。第二個是可以應用於任何控件的屬性。它不是特定於控制。讓我看看我能否找到適當的術語。 – user2453734