使用viewmodel绑定usercontrol的依赖属性

时间:2013-11-19 12:11:02

标签: c# wpf xaml mvvm dependency-properties

基本上,我有一个带有用户控件的主窗口,其中包含一个绑定到主窗口视图模型的属性。这个想法是当属性在用户表单中发生变化时,通过绑定主窗口视图模型中的属性也会发生变化。问题是,当用户控件没有ViewModel时,这是有效的,当我向用户控件添加一个简单的ViewModel时,绑定不再起作用。因为我需要为我的控件设置ViewModel,所以我需要弄清楚为什么添加ViewModel会破坏绑定以及如何修复它。欢迎任何建议。

public partial class Control1 : UserControl, INotifyPropertyChanged
{
   public Control1()
    {
        InitializeComponent();
        Loaded += Control1_Loaded;
    }

    void Control1_Loaded(object sender, RoutedEventArgs e)
    {
        DataContext = new Control1ViewModel();
    }

    public static DependencyProperty SavedStringProperty = DependencyProperty.Register(
       "SavedString", typeof(string), typeof(Control1));
    public string SavedString
    {
        get
        {
            return (string)GetValue(SavedStringProperty);
        }
        set
        {
            SetValue(SavedStringProperty, value);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;


    private void FirePropChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
         SavedString = "Hi";
    }   
}

public class MainWindowViewModel : INotifyPropertyChanged
{
    private string _message = "Hi";
    public string myMessage
    {
        get
        {
          return _message;  
        }
        set
        {
            _message = value;
            FirePropChanged("myMessage");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void FirePropChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }



    private string _savedString;
    public string SavedString
    {
        get
        {
            return _savedString;
        }
        set
        {
            _savedString = value;
            FirePropChanged("SavedString");
        }
    }
}

xaml(在MainWindow中):

<myCtrl:Control1 SavedString="{Binding Path=SavedString, Mode=TwoWay}"/>

cs(我的uc viewmode):

 public class Control1ViewModel : INotifyPropertyChanged
 {
      public event PropertyChangedEventHandler PropertyChanged;       
 }

2 个答案:

答案 0 :(得分:7)

当您的UC拥有自己的Vm时,即它自己的DataContext, 你需要爬上可视树并引用它的父级(Window)DataContext

<myCtrl:Control1 SavedString="{Binding RelativeSource={RelativeSource 
    AncestorType=Window} Path=DataContext.SavedString, Mode=TwoWay}"/>

答案 1 :(得分:0)

还有另一种方法可以用元素名称来编写它:

SavedStrings="{Binding ElementName=uc_name, Path=DataContext.SavedString}"