How to bind multiple viewmodels to a single xaml f

2019-09-21 01:53发布

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.

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.

How to overcome this?

标签: c# wpf xaml mvvm
1条回答
Melony?
2楼-- · 2019-09-21 02:25

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

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

<Window>
...
...
    <Grid DataContext="{Binding G1VM}"/>
    <Grid DataContext="{Binding G2VM}"/>
</Window>
查看更多
登录 后发表回答