使用MVVM更改ContentControl WPF的内容? [英] Change content of ContentControl WPF using MVVM?

查看:362
本文介绍了使用MVVM更改ContentControl WPF的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用将WVM与MVVM一起使用的项目,并且处在困难的境地.

I'm working on a project using MVVM with WPF and I'm in a difficult spot.

当我在其中按钮更改ContentControl内容的窗口中创建ButtonContentControl时,它工作正常.

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>

但是当我使用按钮创建UserControl且按钮更改时,ContentControl的内容不起作用. 为什么?

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>

正在调用ContentControl内容更改的UserControl

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>

谢谢!

推荐答案

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

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>

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

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.

怎么样:

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

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

这篇关于使用MVVM更改ContentControl WPF的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆