双向绑定忽略源更改

时间:2014-06-26 12:02:31

标签: c# wpf mvvm binding

我有自定义控件和依赖属性,绑定到ViewModel属性只能像OneWayToSource一样工作。我搞砸了什么?

结合

<local:MyControl SelectedItem="{Binding SelectedPage}"/>

ViewModel和control

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private ViewModelPageBase _selectedPage;
    public ViewModelPageBase SelectedPage
    {
        get { return _selectedPage; }
        set
        {
            _selectedPage = value;
            OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string property = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

public class MyControl : ContentControl
{
    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set
        {
            // never get here
            SetValue(SelectedItemProperty, value);
        }
    }
    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
        "SelectedItem",
        typeof(object),
        typeof(MyControl),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}

早些时候我使用ItemsControl并且绑定工作是双向的。现在,使用MyControl,只有更改了SelectedItem,才会更新SelectedPage。其他方式(在某处设置SelectedPage)不会更新SelectedItem

想法?

3 个答案:

答案 0 :(得分:2)

在选定的Item Dependency Property声明中,

public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
        "SelectedItem",
        typeof(object),
        typeof(ViewNavigatorControl),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));



typeof(ViewNavigatorControl) should be replaced by typeof(MyControl)

让我知道这是否可以解决问题

答案 1 :(得分:2)

我看到你对依赖属性的setter的评论:

  

公共对象SelectedItem       {           get {return(object)GetValue(SelectedItemProperty); }           组           {                //永远不会到达               SetValue(SelectedItemProperty,value);           }       }

我想您已经知道了,但是如果您不在依赖属性中,则setter永远不会调用,如果您想要通知任何更改,您应该在 FrameworkPropertyMetadata

Setters not run on Dependency Properties?

答案 2 :(得分:1)

我看到两个问题:

首先,您忘记了已关闭的}

SelectedItem="{Binding SelectedPage}"

其次在您的依赖属性上,第三个对象应该是您的所有者类。在你的情况下 MyControl

public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register(
     "SelectedItem",
     typeof(object),
     typeof(**ViewNavigatorControl**),
     new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

但也许这个错误只是一个糟糕的复制/粘贴。