组合框“的SelectedItem绑定到的DependencyProperty是不是清爽 [英] Combobox' SelectedItem bound to a DependencyProperty is not refreshing
问题描述
我有一个组合框,它的SelectedItem绑定到依赖项属性。
I have a combobox, whose SelectedItem is bound to a dependency property.
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 ()
方法调用。
The data is correctly bound and displayed, but when I select another value in the combobox, the set
is not called, neither is my LoadThings()
method called.
有一个明显的原因是什么?
Is there an obvious reason ?
在此先感谢
我用snoop来查看组合框里面,当我改变的值,组合框'的SelectedItem也发生了变化。结果
我也查了code和属性被更改。但我的方法不叫(因为我不经过设置
,所以这个问题依然存在...
I used snoop to view inside the combobox, and when I change the value, the combobox' SelectedItem is also changed.
I also checked in the code, and the property is changed. But my method is not called (as I don't go through the set
, so the problem is still there...
推荐答案
好吧,我发现如何做到这一点。
Ok I found how to do that.
我宣布使用过载woth这样的回调我的DependencyProperty:
I declare my DependencyProperty using the overload woth the callback like this:
public static readonly DependencyProperty SelectedStuffProperty =
DependencyProperty.Register("SelectedStuff", typeof(KeyValuePair<int, string>), typeof(MyUserControl), new UIPropertyMetadata(default(KeyValuePair<int, string>), new PropertyChangedCallback(SelectedStuffChanged));
和回调,我这样做:
private static void SelectedStuffChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyUserControl c = d as MyUserControl;
c.LoadThings();
}
这篇关于组合框“的SelectedItem绑定到的DependencyProperty是不是清爽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!