I'm working on a project using MVVM with WPF and I'm in a difficult spot.
When I create a Button
and a ContentControl
in a window where the button changes the content of the ContentControl
, it works fine.
<Window.Resources>
<me:UserControl1ViewModel x:Key="viewModel" />
</Window.Resources>
<Grid>
<Button Content="Button"
Name="button1"
Command="{Binding Source={StaticResource viewModel}, Path=ClickCommand}" />
<ContentControl Content="{Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Source={StaticResource viewModel}, Path=View, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
</Grid>
But when I create a UserControl with a button and the button changes the content of the ContentControl does not work. Why?
<Window.Resources>
<me:UserControl1ViewModel x:Key="viewModel" />
</Window.Resources>
<Grid>
<v:UserControl1 />
<ContentControl Content="{Binding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Source={StaticResource viewModel}, Path=View, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
</Grid>
UserControl that is calling the change of the contents of the ContentControl
<UserControl.Resources>
<me:UserControl1ViewModel x:Key="viewModelA" />
</UserControl.Resources>
<Grid>
<Button Content="Button"
Name="button1"
Command="{Binding Source={StaticResource viewModelA}, Path=ClickCommand}" />
</Grid>
Thanks!
The simple answer is in your second example you are bound to two different view models.
Basically, your UserControl and Window are not sharing the same view model instance, thus updates are not propagated. You'll need to get the same instance to your user control.
How about: