【问题标题】:Query on MVVM design pattern on WPF在 WPF 上查询 MVVM 设计模式
【发布时间】:2010-03-08 08:42:41
【问题描述】:

我正在使用 MVVM 架构。

我有一个用户控件 UC 作为 View

ModelModelData

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

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

假设 uc1、uc2 和 uc3。

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

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

【问题讨论】:

    标签: wpf mvvm wpf-controls


    【解决方案1】:

    据我了解您的问题,您可以通过让 UC 公开 SelectedSubView(或其他)属性来解决此问题:

    public object SelectedSubView { get; }
    

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

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


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

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

    【讨论】:

    • 感谢 Mark 的回复。您能给我一个关于恢复视图模型或如何在运行时设置视图模型的想法吗?
    • @Ashish Ashu:更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多