【发布时间】:2018-07-09 12:28:42
【问题描述】:
我正在使用这个 DependencyProperty 来存储字符串集合:
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( nameof( ItemsSource ) , typeof( IEnumerable<string> ) , typeof( MyClass) , new FrameworkPropertyMetadata( new List<string>() , FrameworkPropertyMetadataOptions.BindsTwoWayByDefault ) );
在 ItemsSource 的属性中,我试图过滤掉已经选择的字符串。像这样
SetValue( ItemsSourceProperty , source.Except( target ).ToList() );
return (IEnumerable<string>) GetValue( ItemsSourceProperty );
source 包含所有可能的值,定位选择的值。 source.Except(target).ToList() 工作正常,但结果永远不会存储在 DependencyProperty 中。
我做错了什么?
【问题讨论】:
-
如果您正在绑定 ItemsSource 属性(以及其他几个所谓的值源),WPF 会绕过属性设置器并直接调用 SetValue。这就是为什么你不能在属性设置器中调用除
SetValue(ItemsSourceProperty, value)之外的任何东西。这里解释一下:XAML Loading and Dependency Properties -
除此之外,您不能使用
new List<string>()作为默认值。 MyClass 的所有实例都将在同一个集合对象上运行。 -
这一行的最佳位置在哪里:source.Except(target).ToList()?
-
ItemsSourceProperty 的可用默认值是什么?
-
如果有Binding,设置它的Converter。默认值应为 null。
标签: wpf custom-controls dependency-properties