Reputation: 135
In MainWindowViewModel.cs. The constructor is:
public MainWindowViewModel(Window window)
{
...
}
In MainWindow.xaml, I have some UserControls to be included.
<Grid Name="UserControl1">
<local:UserControl1/>
</Grid>
<Grid Name="UserControl2">
<local:UserControl2/>
</Grid>
...
I have tried to set the DataContext for MainWindow hoping that each UserControl will use the same DataContext as MainWindow does, but the result is not as I expect.
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
mainWindowViewModel = new MainWindowViewModel(this);
this.DataContext = mainWindowViewModel;
}
Then I also tried to set the same DataContext for each UserControl, but the result is also wrong, seems only one UserControl can have the correct DataContext in this way.
Finally I removed the DataContext setting in all UserControls but set it here in MainWindow:
<Grid Name="UserControl1">
<local:UserControl1 Loaded="UserControl1_Loaded"/>
</Grid>
<Grid Name="UserControl2">
<local:UserControl2 Loaded="UserControl2_Loaded"/>
</Grid>
...
private void UserControl1_Loaded(object sender, RoutedEventArgs e)
{
mainWindowViewModel = new MainWindowViewModel(this);
this.DataContext = mainWindowViewModel;
}
private void UserControl2_Loaded(object sender, RoutedEventArgs e)
{
mainWindowViewModel = new MainWindowViewModel(this);
this.DataContext = mainWindowViewModel;
}
The results are fine. But I think the way I set the DataContext may not be a good way. Is there a better way to set the DataContext only once and can act on all UserControls? Thanks.
Upvotes: 0
Views: 581
Reputation: 128061
You don't need any code to set the DataContext of your UserControls, because the value of the MainWindow's DataContext is automatically passed to all of its child elements by dependency property value inheritance.
This will however only work if the UserControls do not set their own DataContext, by something like
<UserControl.DataContext>
<local:MyViewModel/>
</UserControl.DataContext>
in their XAML, or
this.DataContext = new MyViewModel();
in their code behind. Remove all such assignments.
Upvotes: 1