我刚刚开始使用 WPF + MVVM。我想我已经掌握了基础知识。但是,我有一个问题(希望不是一个愚蠢的问题)。
我有一个显示客户列表的视图。我想编辑其中一位客户。如何从 List ViewModel 加载带有单独 ViewModel 的编辑视图。
我确信这是一个相当标准的场景,答案相当简单,但我花了很多时间在谷歌上搜索并没有提出任何具体的问题。有人可以指出一个简单的例子吗?
如果我错了并且不简单,那么做这种事情的最佳方法是什么?
执行此操作的一种常见方法(不仅在 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;
}
}