[英]Designerbehavior of custom control with DependencyProperty
我發現帶有DataGrid-CustomControl的xaml設計器有一個奇怪的行為。 那里我有一個DependencyProperty:
public static readonly DependencyProperty CustomizableColumnsProperty =
DependencyProperty.Register(
"CustomizableColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(DataGridCustomizable),
new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
在XAML-Designer中,我具有以下代碼:
<ctrl:DataGridCustomizable
<ctrl:DataGridCustomizable.CustomizableColumns>
... the columns
在覆蓋方法中
protected override void OnInitialized(EventArgs e)
我將CustomizableColumns放入DataGrid Columns(僅在DesignMode中)
現在這是我的通知。 XAML設計器的首次打開(經過新的構建)對CustomizableColumns沒有任何感覺。 因此,在OnInitialized方法中,不會添加任何列!
然后,我關閉並重新打開XAML設計器,只有現在才知道CustomizableColumns,並且OnInitialized方法將CustomizableColumns放入DataGrid Columns。
你知道原因嗎? 感謝您的輸入!
您不得通過屬性元數據設置可變引用類型依賴項屬性的默認值。 控件的所有實例將使用相同的ObservableCollection<DataGridColumn>
對象,除非您明確分配屬性值。
您應該改為通過控件的構造函數中的SetCurrentValue
調用來設置默認值。
public static readonly DependencyProperty CustomizableColumnsProperty =
DependencyProperty.Register(
nameof(CustomizableColumns),
typeof(ObservableCollection<DataGridColumn>),
typeof(DataGridCustomizable));
...
public DataGridCustomizable()
{
SetCurrentValue(CustomizableColumnsProperty,
new ObservableCollection<DataGridColumn>());
}
使用SetCurrentValue
而不是SetValue
可以確保任何Binding,Style Setter或其他依賴項屬性值源仍然可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.