WPF复合Windows和ViewModels

问题描述

| 我有一个WPF
Window
,其中包含几个
UserControls
,那些控件包含另一个。现在,最主要的方法是如何为此窗口创建
ViewModel
以及在何处绑定它。 我确实希望首先需要为每个子控件创建
ViewModel
。     

解决方法

        有几种方法可以做到这一点。 注入虚拟机 我会推荐这种方法。 如果您的窗口是在
App
类中创建的,例如
var window = new MyWindow();
window.Show();
在显示窗口之前,我将分配VM:
var window = new MyWindow();
window.DataContext = GetDataContextForWindow();
window.Show();
如果您的控件之一需要自己的视图模型,请分配VM来创建控件实例。 数据绑定 如果要设置控件的VM,则可以将“ 7”属性绑定到周围VM提供的VM实例。
<Controls:MyControl DataContext={Binding MyControlsVm} />
背后的代码 您可以使用init方法在后面的代码中设置VM,例如
public MyWindow()
{
    InitializeComponent();
    DataContext = CreateViewModel;
}
如果您不想为主页创建虚拟机,可以使用一个技巧:
public MyWindow()
{
    InitializeComponent();
    DataContext = this;
}
并将类背后的代码用作VM。     ,        我将视图视为ViewModel的可视表示形式,因此我喜欢WPF根据要呈现的ViewModel实例选择视图。 我将其称为“视图定位器”模式,我使用此方法来实例化视图,因为我发现它的实现非常简单。 它基本上在应用程序的ѭ11中放入一个条目,告诉WPF使用IValueConverter查找并实例化
ViewModel
时实例化
View
。 因此,一个可行的示例是: 在您的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>
在resources.xaml中:
<DataTemplate DataType=\"{x:Type vm:ViewModelBase}\">
    <ContentControl Content=\"{Binding Converter={StaticResource ViewModelConverter}}\"/>
</DataTemplate>
设置启动窗口控件的``7'',例如
public MainWindow : Window
{
  InitializeComponent();
  DataContext = new MainViewModel();
}
而且您已经完成很多。因此,如果您有这样的
MainViewModel
public class MainViewModel : ViewModelBase
{
  public ChildViewModel1 Child1 {get;set;}
  public ChildViewModel2 Child2 {get;set;}
}
并且您有一个
UserControl
可以像这样解决您的
MainViewModel
<UserControl x:Class=\"MainView\">
  <StackPanel>
    <ContentPresenter Content=\"{Binding Child1}\"/>
    <ContentPresenter Content=\"{Binding Child2}\"/>
  </StackPanel>
</UserControl>
因此,您的
ViewModelConverter
将返回相应View的实例,而无需您付出任何额外的努力。     ,        在子控件问题上,为什么根视图模型的属性之一不能成为要传递给子控件的子视图模型的实例?另一个选择是一个转换器,它将基于非视图模型的属性转换为子视图模型的实例(例如适配器模式)。     ,        您可能对WPF应用程序框架(WAF)的示例应用程序感兴趣。它们显示了如何实例化复合Views和ViewModels以及它们之间如何交互。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...