使用MVVM处理UIElements

时间:2015-02-04 09:46:20

标签: wpf mvvm winrt-xaml

我正在构建一个试图尽可能遵循MVVM的应用程序。它是一个Windows 8商店应用程序和我使用MVVM光。现在让我说使用MainViewModel我有一个MainPage,我也有一个使用UserViewModel的UserControl。 现在我希望能够在MainPage和UserControl之间进行通信,而无需使用任何代码隐藏。在这个简单的场景中,我想从UserControl

中的按钮“点击”MainPage中的按钮

MainPage.xaml中: 在这里,我有一个按钮,我希望点击Usercontroll

中的按钮
 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="MyButton"
                Command="MyCommand"></Button>   


 </Grid>

MainPageViewModel:

 public class MainViewModel : ViewModelBase
    {
        //
    }

UserControll.Xaml 这是我想从MainPage中单击的按钮

 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <Button Content="UcButton"/>

     </Grid>

UserControlViewModel:

public class UserControlViewModel : ViewModelBase
        {
            //
        }

我很想知道如何在MVVM模式之后与UI-Elements进行交互。任何链接或提示赞赏。

2 个答案:

答案 0 :(得分:1)

&#39;清洁&#39; (MVVM方式)这样做是通过让ViewModels进行交互。

因此,如果View1应该在View2中调用某些内容,则View1会在其ViewModel1上触发一个Command。然后ViewModel1应该联系ViewModel2。 ViewModel2将执行所需的操作并通过其属性显示结果。 View2将绑定到属性并显示操作的效果。

ViewModel之间的交互可以通过发布者 - 订阅者模型(消息代理,总线......)完成。在MVVM中,有a Messenger class来保持依赖关系的清洁。

答案 1 :(得分:1)

我无法评论,因为我没有足够的积分,这个问题似乎有点奇怪。是否要单击按钮以使其显示在GUI中,如按钮变为蓝色或是否要在usercontrolViewModel中调用命令。如果是后者你可能会做这样的修复:

<强> MainPage.xaml中

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="MyButton"
            Command="{Binding  UserControlViewModel.SomeUserControlCommand, Source={StaticResource Locator}}"></Button>
    </Grid>

请记住检查ViewModelLocator中您给UserControlViewModel的名称,当然您必须在UserControlViewModel中创建命令:SomeUserControlCommand。

相关问题