簡體   English   中英

如何以編程方式設置附加屬性?

[英]How does setting an attached property programmatically work?

我正在閱讀有關附加屬性的信息,而我剛剛讀到它們可以通過類似於以下內容的方式進行設置:

Grid.SetRow(myElement, 0);

如果這是靜態方法,那么Grid.SetRow()現在應如何將myElement放入哪個Grid 還是以某種方式使myElement與第0行關聯,所以當有一個包含myElement的新Grid對象時,它可以僅檢查myElement應該進入哪一行?

設置附加屬性時,該值僅存儲在元素中,而不是附加屬性所屬的類型。

例如,附加的row屬性是這樣實現的:

public static readonly DependencyProperty RowProperty = ...;

public static void SetRow(UIElement element, int value)
{
    element.SetValue(RowProperty, value);
}

public static int GetRow(UIElement element)
{
    return (int)element.GetValue(RowProperty);
}

因此,當您調用Grid.SetRow ,內部將調用element.SetValue 由於element是依賴項對象,因此它可以存儲那些其他屬性。 您可以將其想象為Dictionary<DependencyProperty, object>內部的Dictionary<DependencyProperty, object> (盡管實際上要復雜得多),您可以使用SetValueGetValue進行訪問。

因此,該值僅存儲在依賴對象本身內部。 現在,當Grid渲染自己時,它將遍歷其子級以調用其測量和布局例程。 它還將為每個子項調用Grid.GetRow ,以查看是否設置了附加的row屬性,並在其自己的布局階段尊重這些選擇。

如果這是靜態方法,那么Grid.SetRow()現在應如何將myElement放入哪個網格中?

不知道

還是以某種方式將myElement與行0關聯起來,所以當有一個包含myElement的新Grid對象時,它可以只檢查myElement應該進入哪一行?

對,就是這樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM