C# WPF组合窗口和视图模型

C# WPF组合窗口和视图模型,c#,.net,wpf,data-binding,mvvm,C#,.net,Wpf,Data Binding,Mvvm,我有一个WPF窗口,其中包含几个用户控件,这些控件包含另一个。现在,如何为这个窗口创建ViewModel最主要的方法是什么,以及在哪里绑定它 我确实希望首先需要为每个子控件创建ViewModel。有几种方法可以做到这一点 注入虚拟机 我推荐这种方法 如果您的窗口是在应用程序中创建的 var window = new MyWindow(); window.Show(); 我会在显示窗口之前分配VM: var window = new MyWindow(); window.DataContext

我有一个WPF
窗口
,其中包含几个
用户控件
,这些控件包含另一个。现在,如何为这个窗口创建
ViewModel
最主要的方法是什么,以及在哪里绑定它


我确实希望首先需要为每个子控件创建
ViewModel

有几种方法可以做到这一点

注入虚拟机 我推荐这种方法

如果您的窗口是在
应用程序中创建的

var window = new MyWindow();
window.Show();
我会在显示窗口之前分配VM:

var window = new MyWindow();
window.DataContext = GetDataContextForWindow();
window.Show();
如果您的某个控件需要自己的视图模型,请在创建控件实例时指定VM

数据绑定 如果要设置控件的VM,可以将
DataContext
属性绑定到周围VM提供的VM实例

<Controls:MyControl DataContext={Binding MyControlsVm} />
如果不想为主页创建VM,可以使用以下技巧:

public MyWindow()
{
    InitializeComponent();
    DataContext = this;
}

只需将代码隐藏类用作VM。

我将视图视为ViewModel的可视表示,因此我喜欢WPF根据它要渲染的ViewModel实例来选择视图

我称之为视图定位器模式,我使用它来实例化我的视图,因为我发现它非常容易实现

它基本上会在应用程序的
ResourceDictionary
中添加一个条目,告诉WPF在遇到
ViewModel
时使用一个来查找和实例化
视图

因此一个有效的例子是:

在app.xaml中:

<Application x:Class="MyApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml" >
    <Application.Resources>
        <ResourceDictionary Source="Resources.xaml"/>
    </Application.Resources>
</Application>
你差不多完成了。因此,如果您有一个像这样的
MainViewModel

public class MainViewModel : ViewModelBase
{
  public ChildViewModel1 Child1 {get;set;}
  public ChildViewModel2 Child2 {get;set;}
}
<UserControl x:Class="MainView">
  <StackPanel>
    <ContentPresenter Content="{Binding Child1}"/>
    <ContentPresenter Content="{Binding Child2}"/>
  </StackPanel>
</UserControl>
您有一个
UserControl
,它解析为您的
MainViewModel
,如下所示:

public class MainViewModel : ViewModelBase
{
  public ChildViewModel1 Child1 {get;set;}
  public ChildViewModel2 Child2 {get;set;}
}
<UserControl x:Class="MainView">
  <StackPanel>
    <ContentPresenter Content="{Binding Child1}"/>
    <ContentPresenter Content="{Binding Child2}"/>
  </StackPanel>
</UserControl>


因此,您的
ViewModelConverter
将返回相应视图的实例,而无需您付出任何额外的努力。

关于子控件问题,为什么根视图模型的属性之一不是要传递给子控件的子视图模型的实例?另一个选项是转换器,它将非基于视图模型的属性转换为子视图模型的实例(如适配器模式)。

您可能对的示例应用程序感兴趣。它们显示了如何实例化复合视图和视图模型,以及它们如何相互作用。

您在这里没有提供任何答案,您提供的链接只是指向您的项目,而不是任何特别有用的页面。
<UserControl x:Class="MainView">
  <StackPanel>
    <ContentPresenter Content="{Binding Child1}"/>
    <ContentPresenter Content="{Binding Child2}"/>
  </StackPanel>
</UserControl>