在 WPF 上查询 MVVM 设计模式 [英] Query on MVVM design pattern on WPF

查看:27
本文介绍了在 WPF 上查询 MVVM 设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 MVVM 架构.

I am using MVVM architecture.

我有一个用户控件 UC 作为 视图

I have a usercontrol UC as a View

Model 是一个 ModelData

ViewModel (UCViewModel) 绑定到用户控件.

ViewModel (UCViewModel) is binded to a usercontrol.

我在用户控件 UC 中还有另外三个用户控件(如上所述).

I have three more usercontrols that is inside the usercontrol UC ( discussed above).

假设有 uc1、uc2 和 uc3.

Let's say uc1, uc2 and uc3.

并且 UC 中 uc1 、 uc2 和 uc3 的可见性取决于选择的类型(选择哪个单选按钮).

and the visibility of uc1 , uc2 and uc3 inside UC depends on the type selected ( which ever radio button is selected ).

由于 UC 绑定到 UCViewModel,我必须在 UCViewModel 中完成与 uc1、uc2 和 uc3 相关的所有工作.我可以将 VM 与 uc1、uc2 和 uc3 分开吗?如果可以,我该怎么做?请帮忙!!

Since UC is binded to UCViewModel and I have to do all the stuff related to uc1 , uc2 and uc3 inside UCViewModel. Can I have seperate VM to uc1 , uc2 and uc3.. if Yes how can i do that ? Please Help!!

推荐答案

据我了解您的问题,您可以通过让 UC 公开一个 SelectedSubView (或其他)财产:

As far as I understand your question, you can solve this by having UC expose a SelectedSubView (or whatever) property:

public object SelectedSubView { get; }

同时,您将单选按钮绑定到UC 的其他属性并相应地更新SelectedSubView(记得实现INotifyPropertyChanged).根据选定的单选按钮属性,SelectedSubView 必须返回适当的 ViewModel.

At the same time, you bind the radiobuttons to other properties of UC and update SelectedSubView accordingly (remember to implement INotifyPropertyChanged). Based on the selected radiobutton properties, the SelectedSubView must return the appropriate ViewModel.

然后绑定一个 ContentPresenterSelectedSubView 属性并使用 DataTemplates 根据当前 SelectedSubView 的类型选择正确的用户控件(uc1、uc2 或 uc3).

You then bind a ContentPresenter to the SelectedSubView property and use DataTemplates to select the correct user controls (uc1, uc2 or uc3) based on the type of the current SelectedSubView.

由于您只想隐藏非活动视图,因此最好保留它们各自的 ViewModel,因此您可能希望将它们设置为 UC 类中的字段

Since you only want to hide inactive Views, it's probably best to keep their respective ViewModels around, so you may want to make them fields in the UC class

public class UC
{
    private MyFirstViewModel vm1;
    private MySecondViewModel vm2;
    private MyThirdViewModel vm3;
    private object selectedVM;

    public object SelectedSubView
    {
        get { return this.selectedVM; }
    }

    // This method should be called whenever one of the radio buttons
    // are updated (from their bindings)
    private void UpdateSelectedView()
    {
        this.selectedVM = // pick from vm1, vm2, vm3 according to radio button

        // Remember to raise INotifyPropertyChanged for SelectedSubView
    }
}

这篇关于在 WPF 上查询 MVVM 设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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