Change content of ContentControl WPF using MVVM?

2019-02-19 17:18发布

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!

标签: wpf mvvm
1条回答
Melony?
2楼-- · 2019-02-19 17:36

The simple answer is in your second example you are bound to two different view models.

<Window.Resources>
    <!-- View Model Instance #0 -->
    <me:UserControl1ViewModel x:Key="viewModel" />
</Window.Resources>

<UserControl.Resources>
    <!-- View Model Instance #1 -->
    <me:UserControl1ViewModel x:Key="viewModelA" />
</UserControl.Resources>

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:

<!-- Window -->
<v:UserControl1 DataContext="{Binding Source={StaticResource viewModel}}" />

<!-- UserControl1 -->
<Button Content="Button"
        Name="button1"
        Command="{Binding Path=ClickCommand}" />
查看更多
登录 后发表回答