【发布时间】:2013-04-19 09:20:56
【问题描述】:
通过了Edward Tanguay 的一系列问题,这些问题反映了 MVVM 用于 WPF 应用程序的使用,这些问题可以在他的Fat Models, skinny ViewModels and dumb Views, the best MVVM approach? 的链接侧边栏中找到,我对他有点困惑 Big smart ViewModels, dumb Views, and any model, the best MVVM approach? 中的最终 WPF 应用程序
它的M (Model) is Customer class:
//model
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime TimeOfMostRecentActivity { get; set; }
public static Customer GetCurrentCustomer()
{
return new Customer
{ FirstName = "Jim"
, LastName = "Smith"
, TimeOfMostRecentActivity = DateTime.Now
};
}
}
返回当前用户。有点,因为它返回新创建的“当前”用户的副本......
但是 M 的数据在哪里存储和更新以备不时之需?
假设,我想将模型的当前用户FirstName 更改为“Gennady”?
我添加了一个按钮,用于使用此按钮单击事件处理程序更新模型:
private void button1_Click(object sender, RoutedEventArgs e)
{
}
旨在从中更改模型的数据,这些数据将反映在 GUI 中。
我怎样才能做到这一点,通过单击此按钮...抱歉,将代码放入此 button1_Click()?
还是我的愿望有问题?
然后。如何正确更新/更改 MVVM 中的 M ?
更新:
所有答案似乎都是指我不应该在 M 中进行更改,而是在 VM 上进行更改。
虽然我已经特别询问了referenced M-V-VM implementation:
public CustomerViewModel()
{
_timer = new Timer(CheckForChangesInModel, null, 0, 1000);
}
private void CheckForChangesInModel(object state)
{
Customer currentCustomer = CustomerViewModel.GetCurrentCustomer();
MapFieldsFromModeltoViewModel(currentCustomer, this);
}
public static void MapFieldsFromModeltoViewModel
(Customer model, CustomerViewModel viewModel)
{
viewModel.FirstName = model.FirstName;
viewModel.LastName = model.LastName;
viewModel.TimeOfMostRecentActivity = model.TimeOfMostRecentActivity;
}
因此,例如,在实现代码from Adolfo Perez's answer 更改时,TextBox 的内容仅在_timer = new Timer(CheckForChangesInModel, null, 0, 1000); 中设置的时间间隔内从“Jim”更改为“Gennady”。
referenced by me M-V-VM in WPF approach 的所有逻辑都应该更新 “M”,以便 VM 赶上这些变化,而不是“VM”。
我更不明白,如果要在 VM 中进行更改,如果 VM 知道 VM 怎么能反映在 M 中strong>M 但 - 反之亦然 - 模型不知道 ViewModel)。
【问题讨论】:
-
自标题问题以来将问题标记为已回答:“如何(正确)更新 WPF 应用程序的 MVVM 中的 M?”尽管我应该以不同的方式提出问题,但得到了回答。比如,“如何在这种特定风格的 M-V-VM 中更新 M?”
标签: c# wpf mvvm conceptual