使用MVVM绑定MainWindow上的UserControl View模型

我是WPF和MVVM的新手,我正在努力学习WPF如何使用MVVM。 为此,我做了如下样本

UserControl1.xaml

   

UserControl1ViewModel.cs

 class UserControl1ViewModel { public string MyString { get; set; } } 

MainWindow.xaml

   //tried binding the Usercontrol1VM obj on MainWindowVM 

MainWindow.xaml.cs

 public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowViewModel(); } 

MainWindowViewModel.cs

 class MainWindowViewModel { public MainWindowViewModel() { ShowMeOne = new RelayCommand(Prompt_ShowMeOne); ShowMeAnother = new RelayCommand(Prompt_ShowMeAnother); UC1Property.MyString = "Initial"; } private void Prompt_ShowMeAnother(object obj) { global::System.Windows.MessageBox.Show("Another Should be shown"); UC1Property.MyString = "Last Clicked: Another"; } private void Prompt_ShowMeOne(object obj) { global::System.Windows.MessageBox.Show("One Should be shown"); UC1Property.MyString = "Last Clicked: One"; } public ICommand ShowMeOne { get; set; } public ICommand ShowMeAnother { get; set; } //UserControl1 View Model for MainWindow public UserControl1ViewModel UC1Property { get; set; } } 

问题:现在,我如何将Usercontrol的Datacontext传递给MainWindow?

 -----------------------------In MainWindow.xaml----------------------  //tried binding the Usercontrol1VM obj on MainWindowVM -----------------------------In MainWindowViewModel.cs--------------- //UserControl1 View Model for MainWindow public UserControl1ViewModel UC1Property { get; set; } 

我尝试的上面的代码没有按预期工作。 在窗口上传递usercontrol的datacontext的标准方法是什么?

你对MVVM,Views和UserControls有一个普遍的误解。

UserControl是一种可重用的代码,不是特定于某种应用程序的。 话虽这么说,当你创建一个新的UserControl时,没有UserControl

UserControl是自我维持的,用户控制所需的所有逻辑都在代码中。 为了说清楚,这违反MVVM模式。 MVVM模式适用于Views和ViewModel以及它们如何交互。

View (纯XAML,无逻辑)之间存在细微差别。 视图通常也inheritance自UserControl ,但View只适用于您正在开发的应用程序。 您不太可能在其他应用程序中重用此function。

这是UserControl之间的区别。 例如,日历用户控件是可重用的,并且选择和显示日历的所有逻辑都是其控制代码的一部分,您可以在许多类型的应用程序中使用它。

当您创建使用数据绑定的UserControl ,您需要在用户控件中公开依赖项属性,在日期选择器用户控件上,这可能是MinDateMaxDateSelectedDateFirstDayOfTheWeek (星期日或星期一)和/或控制的属性格式化并隐藏UserControl的XAML中的所有其他属性(不通过依赖属性公开它们)。