如何将多个视图模型绑定到 MVVM wpf 中的单个 xaml 文件? [英] How to bind multiple viewmodels to a single xaml file in MVVM wpf?

查看:31
本文介绍了如何将多个视图模型绑定到 MVVM wpf 中的单个 xaml 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mainwindow.xaml 中有三个网格,每个网格中有多个控件.对于每个网格,我都创建了一个单独的视图模型.

I have three grids in Mainwindow.xaml with multiple controls in each grid. For each of the grids, I have created a separate view model.

但在 Mainwindow.xaml 中,我只能将 DataContext 属性设置为其中一个类,这样只能将数据绑定到其中一个网格.

But in Mainwindow.xaml, I am able to set DataContext property to only one of the classes, which enables only data binding to one of the grid.

如何克服这个问题?

推荐答案

解决方案很少.首先,您可以在 MainViewModel 中添加 ViewModels,它看起来像:

There are few ways for it. First, you can add ViewModels in your MainViewModel, so it will look like:

  public class MainViewModel
{
    public Grid1ViewModel G1VM {get;set;}
    public Grid2ViewModel G2VM {get;set;}
}

然后在您的窗口中,您应该将其数据上下文设置为:

then in your Window, you should set it's data context like:

public class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new MainViewModel()
        {
            G1VM = new Grid1ViewModel(),
            G2VM = new Grid2ViewModel()
        };
    }
}

然后在 MainWindow.xaml 中,您可以为不同的网格设置数据上下文,例如:

Then in your MainWindow.xaml you can set a datacontext for different Grids like:

<Window>
...
...
    <Grid DataContext="{Binding G1VM}"/>
    <Grid DataContext="{Binding G2VM}"/>
</Window>

这篇关于如何将多个视图模型绑定到 MVVM wpf 中的单个 xaml 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆