Wpf 绑定到DependencyProperty的组合框“SelectedItem”未刷新
我有一个组合框,它的SelectedItem绑定到一个依赖属性Wpf 绑定到DependencyProperty的组合框“SelectedItem”未刷新,wpf,binding,combobox,dependency-properties,selecteditem,Wpf,Binding,Combobox,Dependency Properties,Selecteditem,我有一个组合框,它的SelectedItem绑定到一个依赖属性 public IEnumerable<KeyValuePair<int,string>> AllItems { get { return _AllItems; } set { _AllItems = value; this.NotifyChange(() => AllItems); } } public KeyValuePair<i
public IEnumerable<KeyValuePair<int,string>> AllItems
{
get { return _AllItems; }
set
{
_AllItems = value;
this.NotifyChange(() => AllItems);
}
}
public KeyValuePair<int, string> SelectedStuff
{
get { return (KeyValuePair<int, string>)GetValue(SelectedStuffProperty); }
set
{
SetValue(SelectedStuffProperty, value);
LoadThings();
}
}
public static readonly DependencyProperty SelectedStuffProperty =
DependencyProperty.Register("SelectedStuff", typeof(KeyValuePair<int, string>), typeof(MyUserControl), new UIPropertyMetadata(default(KeyValuePair<int, string>)));
以及xaml:
<ComboBox DisplayMemberPath="Value"
ItemsSource="{Binding AllItems}"
SelectedItem="{Binding SelectedStuff, Mode=TwoWay}" />
数据被正确绑定和显示,但是当我在组合框中选择另一个值时,集合不会被调用,LoadThings方法也不会被调用
有明显的原因吗
提前谢谢
编辑
我使用snoop在组合框内查看,当我更改值时,组合框的SelectedItem也会更改。
我还签入了代码,属性也被更改了。但是我的方法没有被调用,因为我没有遍历集合,所以问题仍然存在…来自
在除特殊情况外的所有情况下,您的包装器实现
应该分别只执行GetValue和SetValue操作。
其原因将在XAML加载和更新主题中讨论
依赖属性
你可以阅读
WPF XAML处理器使用属性系统方法作为依赖项
加载二进制XAML和处理以下属性时的属性
依赖属性。这实际上绕过了属性
包装纸
好的,我找到了方法 我使用重载WO和回调声明DependencyProperty,如下所示:
public static readonly DependencyProperty SelectedStuffProperty =
DependencyProperty.Register("SelectedStuff", typeof(KeyValuePair<int, string>), typeof(MyUserControl), new UIPropertyMetadata(default(KeyValuePair<int, string>), new PropertyChangedCallback(SelectedStuffChanged));
SelectedStuffProperty需要成为DependencyProperty是否有原因?这会将大部分控制权从您手中夺走,并将其置于框架的法庭上。像这样的大多数情况只需要一个引发属性更改通知的标准属性。是的,它是UserControl的一部分,我必须通过父容器中的绑定从中获取此值。感谢您提供的信息,我现在理解了为什么不能使用断点!
private static void SelectedStuffChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyUserControl c = d as MyUserControl;
c.LoadThings();
}