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?
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>