Combobox' SelectedItem bound to a DependencyProperty is not refreshing

百般思念 提交于 2019-12-13 00:33:49

问题


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>)));

And the xaml:

<ComboBox DisplayMemberPath="Value"
          ItemsSource="{Binding AllItems}"
          SelectedItem="{Binding SelectedStuff, Mode=TwoWay}" />

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 ?

Thanks in advance


Edit

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...


回答1:


From MSDN

In all but exceptional circumstances, your wrapper implementations should perform only the GetValue and SetValue actions, respectively. The reason for this is discussed in the topic XAML Loading and Dependency Properties.

And there you can read

The WPF XAML processor uses property system methods for dependency properties when loading binary XAML and processing attributes that are dependency properties. This effectively bypasses the property wrappers.




回答2:


Ok I found how to do that.

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));

And in the callback, I do this:

private static void SelectedStuffChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyUserControl c = d as MyUserControl;
    c.LoadThings();
}


来源:https://stackoverflow.com/questions/16697120/combobox-selecteditem-bound-to-a-dependencyproperty-is-not-refreshing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!