具有 DependencyProperty 的自定义控件的 Designerbehavior

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 列(仅在设计模式中)

现在这是我的通知。 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 可确保任何绑定、样式 Setter 或其他依赖项 属性 值源仍然正常工作。