从 XAML (WPF) 设置集合 DependencyProperty

Setting a collection DependencyProperty from XAML (WPF)

我创建了一个用户控件 (FilterPicker),它有一个特定的列表作为 属性。这是一个依赖属性所以我在使用用户控件的时候可以设置它。

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
        "Strategies",
        typeof(List<FilterType>),
        typeof(FilterPicker),
        new FrameworkPropertyMetadata
        {
            DefaultValue = new List<FilterType> { FilterType.Despike },
            PropertyChangedCallback = StrategiesChangedCallback,
            BindsTwoWayByDefault = false,
        });

然后我尝试在我使用此控件的 .xaml 文件中定义此列表。

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}">
            <Filtering:FilterPicker.Strategies>
                <Filtering1:FilterType>PassThrough</Filtering1:FilterType>
                <Filtering1:FilterType>MovingAverage</Filtering1:FilterType>
                <Filtering1:FilterType>Despike</Filtering1:FilterType>
            </Filtering:FilterPicker.Strategies>
        </Filtering:FilterPicker>

然而,它不起作用。 StrategiesChangedCallBack 永远不会被调用。 如果我通过绑定设置它,它工作正常 - 只是当我尝试在 xaml 中定义它时不行。所以这有效:

<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}" Strategies="{Binding AllStrategies}">

但不是前面的片段。关于我做错了什么的想法?

根据对我最初问题的评论,我能够将其拼凑起来:

  • 确实,问题是我只听到 属性 被更改,而不是集合中的对象。
  • 正如预测的那样,我在同一个集合实例上运行时遇到了问题。

最后,我将 DependencyProperty 更改为使用 IEnumerable,我将其定义为 .xaml 中使用 FilterPicker UserControl 的 StaticResource。

依赖属性:

public static readonly DependencyProperty StrategiesProperty = DependencyProperty.Register(
        "Strategies",
        typeof(IEnumerable<FilterType>),
        typeof(FilterPicker),
        new FrameworkPropertyMetadata
        {
            DefaultValue = ImmutableList<FilterType>.Empty, //Custom implementation of IEnumerable
            PropertyChangedCallback = StrategiesChangedCallback,
            BindsTwoWayByDefault = false,
        });

使用它:

<Grid.Resources>
            <x:Array x:Key="FilterTypes" Type="{x:Type Filtering1:FilterType}" >
                <Filtering1:FilterType>PassThrough</Filtering1:FilterType>
                <Filtering1:FilterType>MovingAverage</Filtering1:FilterType>
                <Filtering1:FilterType>Fir</Filtering1:FilterType>
            </x:Array>
        </Grid.Resources>

<Filtering:FilterPicker Grid.Row="1" Strategies="{StaticResource FilterTypes}" />