我创建了一个用户控件 (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
永远不会被调用。
如果我通过绑定(bind)设置它,它就可以正常工作 - 只是当我尝试在 xaml 中定义它时就不行了。所以这有效:
<Filtering:FilterPicker Grid.Row="1" Strategy="{Binding Strategy}" Strategies="{Binding AllStrategies}">
但不是之前的片段。关于我做错了什么有什么想法吗?
最佳答案
根据对我最初问题的评论,我能够将其拼凑起来:
- 事实上,问题是我只监听正在更改的属性,而不是集合中的对象。
- 正如预测的那样,我在同一集合实例上运行它时遇到了问题。
最后,我将 DependencyProperty 更改为使用 IEnumerable,我将其定义为使用 FilterPicker UserControl 的 .xaml 中的 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}" />
关于c# - 从 XAML (WPF) 设置集合 DependencyProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40346287/