【问题标题】:WPF MVVM Single ViewModel for Display and Editing用于显示和编辑的 WPF MVVM 单一 ViewModel
【发布时间】:2013-01-14 10:34:48
【问题描述】:

我正在使用来自Josh Smith 的示例。他有一个显示 CustomerViewModel 列表的 WorkspaceViewModel。他使用相同的 ViewModel 来显示所有客户和编辑一个客户。

这是一个好习惯吗?如果我有一个 CustomerViewModels 列表,我不需要 SaveCommand 或 CloseCommand 或一些 IsSelected 标志。

有一个单独的 EditCustomerViewModel 更好吗?但是如何处理与 Workspace 相关的东西呢?例如:

public class Workspace : ViewModel
{
    public ICommand CloseCommand;
}

public class AllCustomers : Workspace
{
    public ObservableCollection<CustomerViewModel> CustomerViewModels;
}

// Option A (one ViewModel for display and edit):
public class CustomerViewModel : ? 
{
    public string CustomerName;
    public ICommand SaveCommand;    
}

或分离:

// Option B:
public class CustomerViewModel : ViewModel 
{
    public string CustomerName;
}

public class EditCustomerViewModel : Workspace
{
    public CustomerViewModel CustomerViewModel;
    public ICommand SaveCommand;
}

// Option C (CustomerViewModel does not need CloseCommand but EditCustomerViewModel does):
public class CustomerViewModel : Workspace 
{
    public string CustomerName;
}

public class EditCustomerViewModel : CustomerViewModel
{   
    public ICommand SaveCommand;    
}

编辑: 我试图澄清我的问题。在 Josh Smith 示例中的 CustomerViewModel 中,他有关闭和保存客户的命令。在 AllCustomerView 中,他有一个绑定到 CustomerViewModels 的 ObservableCollection 的 GridView。但在 GridView 中,这两个命令都不是必需的。在 GridView 中我可以忽略这两个命令,但这是一个好的设计吗?

【问题讨论】:

  • 从您的选项 a 中选择一个,在选项 b 中,客户是模型​​而不是视图模型,在 c 中通过继承,您需要按视图划分视图模型。
  • 如果是 Josh Smith,那么是的,这是一个“好习惯”。

标签: wpf mvvm viewmodel


【解决方案1】:

我不太清楚您的意思,因为快速浏览该文章表明他同时使用列表和视图/编辑视图模式,分别称为 AllCustomers­ViewModelCustomerViewModel。这肯定是推荐的做法,而不是使用具有多个职责的单一视图模型。

这两个视图模型都继承自 WorkspaceViewModel,这增加了他的工作区功能。所以,总而言之,如果你想构建类似的东西,我会遵循他的模式。您还应该认真考虑一个 MVVM 框架,例如 Caliburn.Micro,它添加了基于约定的简单视图组合以及屏幕生命周期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2010-11-10
    • 2012-10-09
    • 2020-11-04
    • 1970-01-01
    • 2013-12-09
    • 2016-07-17
    相关资源
    最近更新 更多