MVVM针对同一对象的多个演示?

时间:2013-01-07 04:22:55

标签: wpf mvvm

我需要以不同方式呈现一个对象,两次。

  1. 作为TreeView中的节点(导航/重命名)
  2. as 2 TextBoxes(重命名/编辑内容)
  3. public class Item
    {
        public string Name{get;set;}
        public string Content{get;set;}
    }
    

    我的第一个解决方案是保持简单:

    public class MainViewModel
    {
        // collection of items (treeview navigation)
        public BindingList<ItemViewModel> Items{get;set;}
    
        // selected item (from treeview navigation)
        // used for textbox edit
        public ItemViewModel SelectedItem{get;set;}
    }
    
    public class ItemViewModel
    {
        // Used for treeview navigation
        public bool IsSelected{get;set;}
        public bool IsExpanded{get;set;}
        public bool IsInEditNameMode{get;set;}
        public BindingList<ItemViewModel> Children{get;set;}
        public void BuildChildren();
    
        // Used for treeview display/rename
        // Used for textbox display/rename
        public string Name{get;set;}
    
        // Used for textbox edit
        public string Content{get;set;}
    }
    

    这种方法很有效。 但随着应用程序变得越来越复杂,视图模型越来越受到“污染”。

    例如,为同一视图模型添加其他演示文稿(高级属性,图表表示等)

    public class ItemViewModel
    {
        // Used for Advanced properties
        public BindingList<PropertyEntry> Properties {get;set;}
        public PropertyEntry SelectedProperty{get;set;}
    
        // Used for graph relationship
        public BindingList<ItemViewModel> GraphSiblings{get;set;}
        public bool IsGraphInEditNameMode{get;set;}
        public bool IsSelectedGraphNode {get;set;}
        public void BuildGraphSiblings();
    
        // Used for treeview navigation
        public bool IsNavigationInEditNameMode{get;set;}
        public bool IsSelectedNavigationNode{get;set;}
        public bool IsExpandedNavigationNode{get;set;}
        public BindingList<ItemViewModel> NavigationChildren{get;set;}
        public void BuildNavigationChildren();
    
        // Used for treeview display/rename
        // Used for textbox display/rename
        // Used for graph display
        // Used for Advanced properties display
        public string Name{get;set;}
    
        // Used for textbox edit
        public string Content{get;set;}
    }
    

    目前,我仍在使用单一视图模型进行多个演示,因为它可以使所选项目在所有演示文稿中保持同步。

    此外,我不必保留重复的属性(名称/内容)。

    最后,PropertyChanged通知有助于更新项目的所有表示(即,在导航更新TextBox / Graph / Advanced属性/等中更改名称)。

    但是,这也违反了几项原则(单一责任,最低权限等)。

    但是我不太确定如何重构它,而不需要编写大量代码来保持同步/属性通知在每个新视图模型中保持工作/复制模型的属性等等。

    我想知道的是:

    如果由您决定,您将如何解决这个问题?

    目前,一切仍然有效。我觉得代码可以进一步改进,这就是我需要帮助的地方。

2 个答案:

答案 0 :(得分:1)

如何使用继承?拥有一个基本的ItemViewModel,然后将其子类化以创建一个TreeViewItemViewModel,您可以在其中添加与子类中此项目的树视图呈现相关的属性。

答案 1 :(得分:0)

我们可以,

  1. 尝试从ItemViewModel类中分离出各种特定于视图的行为。
  2. 将视图特定行为放置/封装在单独的类(行为类)中。
  3. 这使您可以在运行时灵活地实例化/注入/切换行为。 是的,尝试使用策略模式来制作更清晰,单一责任,易于维护的代码。

相关问题