我对MVVM有些新意.我不确定做我想做的最好的方法是什么.
这是场景:
我有一个将要显示另一个窗口的VM.我可以打电话myNewWindowView.Show(),但首先我需要在新窗口的VM中设置一些数据.
我应该同时公开myNewWindowView和NewWindowViewModel调用ViewModel吗?
这是一个例子:
class MainVM
{
public void FindCustomer(string nameParial)
{
List<Customer> customers = ServiceCall.GetCustomers(nameParital);
// This is the part I am not sure how to do. I am not sure if this
// View Model should have a reference to a different view model and
// the view too.
myNewWindowViewModel.CustomerList = customers;
myNewWindowView.Show();
}
}
Run Code Online (Sandbox Code Playgroud)
我会将视图模型与任何视图分开。我倾向于将它们视为层,但它们只能在一个方向上互换。
因此 foo 类型的模型可以在其之上放置任何视图模型,并且它从不期望或关心视图模型类型。
视图模型只能用于一种类型的模型,但它不关心或期望什么类型的视图将使用它。
视图将用于特定类型的视图模型。
你似乎拥有一个视图模型,它关心视图正在做什么,这对我来说似乎是错误的。
如果是我,我会获取 MainVM 的视图来显示新窗口,让 MainVM 为新窗口传递适当的视图模型。
这是我将放在主视图模型视图后面的代码
class MainWindow : Window
{
public MainWindow()
{
Initialize();
DataContext = new MainVM();
}
public void FindCustomerClick(object sender, RoutedEventArgs args)
{
CustomerListView clv = new CustomerListView();
clv.DataContext = (DataContext as MainVM).FindCustomer(search.Text);
clv.Show();
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,视图模型有一个方法,它接受一个字符串并返回一个 CustomerListViewModel,然后将其应用于 CustomerListView 的 DataContext。
| 归档时间: |
|
| 查看次数: |
2132 次 |
| 最近记录: |