2013-06-18 56 views
3

我正在讀關於如何做一個參數化的風格(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才能獲得價值,而另一個則不需要?你在不同的場景中使用它們嗎?

+0

他們除了他們使用的是不同的一樣。第一種方法使用靜態方法所以這將允許設置使用語法像控制值:Control.GetTickBrush([InstanceOfTheControl])。第二種方法可讓您通過實例對象訪問這些值。所以你必須做Control test = new control(); test.MyProperty獲取或設置值。 – user2453734

+0

@ user2453734:他們*不*相同。請注意,有兩種不同的方法用於註冊它們。 –

+0

良好的捕獲,一個用於控制,它有一個我屬性類型的屬性(第二個例子)。第二個是可以應用於任何控件的屬性。它不是特定於控制。讓我看看我能否找到適當的術語。 – user2453734

回答

4

您展示的第一個例子是一個attached property,這是一種特殊的依賴項屬性。附加屬性的值可以「附加」到其他對象,而通常的依賴屬性屬於它們各自類的實例。

第二個代碼片段展示了一個普通依賴屬性,是去,如果你只是想一個額外的依賴屬性添加到您要創建一個自定義類的方式。

+0

謝謝!我沒有意識到這一點。 –