从XAML (WPF)设置一个集合DependencyProperty

本文关键字:一个 DependencyProperty 集合 设置 XAML WPF | 更新日期: 2023-09-27 18:15:45

我创建了一个用户控件(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}">

但不是前面的代码片段。你知道我哪里做错了吗?

从XAML (WPF)设置一个集合DependencyProperty

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

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

最后,我改变了我的DependencyProperty来使用IEnumerable,我在.xaml中定义为使用FilterPicker UserControl的StaticResource。

DependencyProperty:

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}" />
相关文章: