我刚刚开始使用WPF + MVVM。我想我已经掌握了基础知识。但是,我有一个问题(希望不是一个愚蠢的问题)。
我有一个显示客户列表的视图。我想编辑其中一个客户。如何使用List ViewModel中的单独ViewModel加载编辑视图。
我确信这是一个相当标准的场景,有一个相当简单的答案,但我花了一大块时间谷歌搜索并没有具体的东西。有人能指出我一个直截了当的例子吗?
如果我错了并且不是直截了当,那么做这种事情的最佳方式是什么?
答案 0 :(得分:3)
执行此操作的常用方法(不仅在MVVM中,但它适用得很好)是让列表VM访问所谓的服务。然后,该服务实现创建和显示编辑器(它可能使用另一个服务)。
示例:
/// Always use an interface for the service: it will make it a breeze
/// to test your VM as it decouples it from the actual service implmentation(s)
interface ICustomerEditorService
{
/// Do whatever needed to get the user to edit the Customer passed in,
/// and return the updated one or null if nothing changed.
/// Customer here is likeyly your customer model, or whatever is neede
/// to represent the editable data
Customer EditCustomer( Customer toEdit );
}
class ListViewModel
{
/// service gets passed to constructor, you can use dependency injection
/// like MEF to get this handled easily;
/// when testing, pass a mock here
public ListViewModel( ...., ICustomerEditorService editorService )
{
....
}
private void OnEditButtonClicked()
{
var editedCustomer = editorService.EditCustomer( GetSelectedCustomer() );
//do stuff with editedCustomer
}
}
/// A real implementation
class CustomerEditorService
{
public Customer EditCustomer( Customer toEdit )
{
var vm = new CustomerEditorViewModel( toEdit );
var view = new CustomerEditorView( vm );
if( myWindowManager.ShowDialog( view ) == Cancel )
return null;
return vm.Customer;
}
}