用于显示和编辑的 WPF MVVM 单一 ViewModel

标签 wpf mvvm viewmodel

我正在使用 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 中,他有一个绑定(bind)到 CustomerViewModels 的 ObservableCollection 的 GridView。但在 GridView 中,这两个命令都不是必需的。在 GridView 中我可以忽略这两个命令,但这是一个好的设计吗?

最佳答案

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

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

关于用于显示和编辑的 WPF MVVM 单一 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14316794/

相关文章:

c# - WPF-MVVM多项目结构

asp.net-mvc - ASP.NET MVC 模型/ View 模型验证

design-patterns - 在域模型之间映射数据的模式

wpf - 根据 DataTable 值对 DataGrid 行着色

c# - 带有 MVVM 和 CommandParameter 的 ListBox SelectionChanged 事件

c# - 使用数据注释的 WPF MVVM 验证

c# - 如何将控件绑定(bind)到 MVVM 中的 visualbrush?

c# - MVC 3 - Controller 和 ViewModels - 哪个应该包含大部分业务逻辑?

wpf - 从图像创建矢量

c# - WPF 在触发条件下无法将 "Red"的静态资源识别为红色画笔