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; }解决方法 当您的UC拥有自己的Vm,即它自己的DataContext时,
你需要爬上可视树并引用它的父级(Window)DataContext
<myCtrl:Control1 SavedString="{Binding relativeSource={relativeSource AncestorType=Window} Path=DataContext.SavedString,Mode=TwoWay}"/>总结
以上是内存溢出为你收集整理的c# – 使用viewmodel绑定usercontrol的依赖属性全部内容,希望文章能够帮你解决c# – 使用viewmodel绑定usercontrol的依赖属性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)