使用 MVVM 更改 ContentControl WPF 的内容?

2023-12-10

我正在开发一个使用 MVVM 和 WPF 的项目,但我遇到了困难。

当我创建一个Button and a ContentControl在按钮更改内容的窗口中ContentControl,效果很好。

<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 的内容时不起作用。 为什么?

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

正在调用 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>

Thanks!


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

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

基本上,您的 UserControl 和 Window 不共享相同的视图模型实例,因此不会传播更新。您需要为您的用户控件获取相同的实例。

怎么样:

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

<!-- UserControl1 -->
<Button Content="Button"
        Name="button1"
        Command="{Binding Path=ClickCommand}" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 MVVM 更改 ContentControl WPF 的内容? 的相关文章

随机推荐