2017-06-15 66 views
0

所以我創建了一個用戶控件,並且我在它上面創建了一個依賴屬性TestProperty。UWP XAML用戶控件靜態屬性與實例屬性

我希望有2個此用戶控件的實例併爲每個實例設置TestProperty爲不同的值。

<widgets:mycontrol Test="val1"></widgets:WTComboBox> 
<widgets:mycontrol Test="val2"></widgets:WTComboBox> 

如果我創建testproperty爲靜態的DependencyProperty如下:

public static readonly DependencyProperty TestProperty= 
     DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null); 
在控制

,那麼顯然我不能在每個實例的一個不同的值,但是當我創建testproperty作爲一個正常的實例屬性

public DependencyProperty TestProperty; 

public mycontrol() 
{ 
    TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null); 
} 

上的控制,那麼設計師不能識別屬性存在,並創建一個錯誤,但在運行時控制完美的作品一nd控件的每個實例都具有測試屬性的正確值。

所以問題是我如何獲得實例dependencyproperty的工作在設計器?

感謝

回答

1

DependencyProperty註冊到一個類型,而不是一個實例。您正確寫入此代碼進行註冊。 Reference from here.

public static readonly DependencyProperty TestProperty= 
    DependencyProperty.Register("Test", typeof(string), typeof(mycontrol), null); 

然後你說,

那麼顯然我不能在每個實例

這是不是真的爲它不同的值。

你可以爲每個實例不同的值,但事件被DependencyProperty以這種方式註冊的,它不是一個靜態屬性只能有該類型的所有實例的一個值,就像你可能除外常規的CLR屬性。要了解依賴屬性和CLR屬性之間的區別,請參閱this answer

然後你定義一個非靜態的依賴項屬性(並詢問如何讓設計者識別這個屬性),你不應該這樣做。已經有some answer爲什麼你不應該寫一個非靜態的依賴屬性,即使它看起來可以工作。