使用MVVM在MainWindow上绑定UserControl视图模型

Gop*_*dar 2 c# wpf xaml user-controls mvvm

我是WPF和MVVM的新手,我正在尝试学习WPF如何与MVVM一起使用。为此,我制作了以下示例

UserControl1.xaml

<StackPanel>
        <TextBox   Text="{Binding MyString}" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

UserControl1ViewModel.cs

class UserControl1ViewModel
{
     public string MyString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml

<StackPanel>
        <local:UserControl1 DataContext="{Binding UC1Property}"/>  //tried binding the Usercontrol1VM obj on MainWindowVM
        <Button Command="{Binding ShowMeOne}" Height="30" Content="ShowOne"/>
        <Button Command="{Binding ShowMeAnother}" Height="30" Content="ShowAnother" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml.cs

public MainWindow()
{
   InitializeComponent();
   this.DataContext = new MainWindowViewModel();
}
Run Code Online (Sandbox Code Playgroud)

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


}
Run Code Online (Sandbox Code Playgroud)

问题:现在,如何将用户控件的数据上下文传递到MainWindow中?

-----------------------------In MainWindow.xaml----------------------
<local:UserControl1 DataContext="{Binding UC1Property}"/>  //tried binding the Usercontrol1VM obj on MainWindowVM
-----------------------------In MainWindowViewModel.cs---------------
//UserControl1 View Model for MainWindow
public UserControl1ViewModel UC1Property { get; set; }
Run Code Online (Sandbox Code Playgroud)

我尝试的上述代码无法正常工作。在窗口上传递用户控件的数据上下文的标准方法是什么?

Tse*_*eng 5

您对MVVM,视图和用户控件有一个普遍的误解。

A UserControl是一段可重用的代码,并不特定于一种应用程序。话虽如此UserControl1ViewModel,当您创建新的时没有UserControl

A UserControl是自我维持的,用户控制所需的所有逻辑都在后面的代码中。明确地说,这并不违反MVVM模式。MVVM模式适用于Views和ViewModels及其交互方式。

View(纯XAML,无逻辑)之间存在细微差别。视图通常也从继承UserControl,但是a View仅在您当前正在开发的应用程序中有用。您极不可能在另一个应用程序中重用它。

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

当您创建UserControl它使用数据绑定,您需要在您的用户控件公开的依赖特性,在一个日期选取器的用户控制,这可能是MinDateMaxDateSelectedDateFirstDayOfTheWeek(周日或周一)和/或性能控制的格式和隐藏所有UserControlXAML 内部的其他属性(通过不通过依赖属性公开它们)。