如何在项目中找到ViewModels?

时间:2012-11-05 23:27:27

标签: c# wpf mvvm

对于MVVM专家来说,这个问题可能听起来很基本,但我正在努力理解我何时应该知道何时需要创建ViewModel以及有多少......好的我已经知道ViewModel是View(UI)和模型(数据),但有时我看到一个应用程序只有2个UI和一个模型,但随后有5个ViewModel参与其中。

事实上,我需要了解的是项目中的哪些现象应该由ViewModel表示?

假设我们有一个电话簿应用程序。所以我假设联系人需要一个UI,例如搜索。显示,编辑和删除确实告诉我需要多少UI。另外,

{
 string firstName,
 string lastName,
 string phone,
 bool isCompany
}

可以是Model的结构。

现在,当它到达ViewModel时我们要处理多少个ViewModel?你怎么认识他们?

我希望这很清楚。

2 个答案:

答案 0 :(得分:3)

根据你的例子,我会像这样安排项目:

  • 联系人[项目]
    • 查看[文件夹]
      • MainWindow.xaml (显示所有联系人的网格和添加/编辑/删除记录的工具栏)
      • CustomerInfo.xaml (包含Customer对象的每个属性的字段的表单)
    • ViewModels [文件夹]
      • MainWindowViewModel.cs (MainWindow的ViewModel)
      • CustomerInfoViewModel.cs (CustomerInfo的ViewModel)
    • 模型
      • Customer.cs

需要注意的一点是,我有CustomerInfo屏幕负责处理添加新客户的逻辑。编辑现有的。基本上有一个重复的表单是没有意义的 - 只需在用户编辑现有客户时填充初始化时每个字段的值。

此外,网格上的删除按钮可以调用execute命令删除所选用户;这也可以从CustomerInfo屏幕完成(删除当前客户)。

答案 1 :(得分:0)

我没有长时间使用MVC,但是,在我的商店中,ViewModel是我们如何构建我们想要传递给Views的数据的方式,其中一种帮助我理解它的方法是可以使用它组合两个或多个模型以在特定视图中使用。

模型 设置你希望你的对象拥有的属性,在这个例子中,Contact返回一个类型“Person”,ContactAddress返回一个类型“Address”(我使用了不同的数据类型,因为我认为它做了一个更清晰的例子,我希望我没有混淆任何事情):

public class Models
{

public Person Contact
{
    // properties of first Model
    string firstName;
    string lastName;
}


public Address ContactAddress 
{
    // properties of second Model
    string Address1;
    string Address2;
    string City;
    string State;
    string Zip;
}
}// EndModels

视图模型 我们知道我们的终端视图将需要联系人数据以及他们的ContactAddress数据。我们可以使用ViewModel来保存两组数据并将其传递给View。

public class ContactVM
{
   // properties of the ViewModel, to hold data for each Model we need to pass to the view 
   public Person Contacts {get; set;}
   public Address ContactAddresses {get;set;} 

   // Constructor
   public ContactVM()
   {
        Contacts = new Person();
        ContactAddresses = new Address();
   }
}

控制器 控制器将调用ViewModel,然后为每个ViewModel调用 使用正确的数据填充它们的属性。有很多方法可以做到这一点,但为了便于举例,我将其排除在外。

public ActionResult Index()
{
    // create an instance of the ViewModel
    ContactVM contacts = new ContactVM();

    // make calls to populate your ViewModel properties with the correct data
    contacts.Contacts = //call to populate your Contact data here
    contacts.ContactAddresses = //call to populate your Address data here

    // pass the ViewModel to the View for use
    return View(contacts);
}