使用MVVM更改ContentControl WPF的内容?

使用MVVM更改ContentControl WPF的内容?,wpf,mvvm,Wpf,Mvvm,我在一个使用MVVM和WPF的项目中工作,我遇到了困难 当我在一个窗口中创建一个按钮和一个内容控件,该按钮可以更改内容控件的内容时,效果很好 <Window.Resources> <me:UserControl1ViewModel x:Key="viewModel" /> </Window.Resources> <Grid> <Button Content="Button" Name="button1

我在一个使用MVVM和WPF的项目中工作,我遇到了困难

当我在一个窗口中创建一个
按钮
和一个
内容控件
,该按钮可以更改
内容控件
的内容时,效果很好

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

但是,当我创建一个带有按钮的UserControl并且该按钮更改了ContentControl的内容时,它就不起作用了。 为什么?


调用ContentControl内容更改的UserControl

<UserControl.Resources>
    <me:UserControl1ViewModel x:Key="viewModelA" />
</UserControl.Resources>

<Grid>
    <Button Content="Button"
            Name="button1"
            Command="{Binding Source={StaticResource viewModelA}, Path=ClickCommand}" />
</Grid>


谢谢

简单的答案是,在第二个示例中,您绑定到两个不同的视图模型

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

基本上,用户控件和窗口不共享同一视图模型实例,因此不会传播更新。您需要将相同的实例添加到您的用户控件中

那么:

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

<!-- UserControl1 -->
<Button Content="Button"
        Name="button1"
        Command="{Binding Path=ClickCommand}" />

您是否正确更改了ViewModel实现InotifyProperty?
<!-- Window -->
<v:UserControl1 DataContext="{Binding Source={StaticResource viewModel}}" />

<!-- UserControl1 -->
<Button Content="Button"
        Name="button1"
        Command="{Binding Path=ClickCommand}" />