0

这个问题对于 MVVM 专家来说可能听起来很基础,但我试图了解我应该如何知道何时需要创建 ViewModel 以及需要创建多少个......好吧我知道 ViewModel 是 View (UI) 和 Model (Data ) 但有时我看到一个应用程序只有 2 个 UI 和一个模型,但其中涉及 5 个 ViewModel。

事实上,我只需要了解一个项目中的哪些现象应该用 ViewModel 来表示?

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

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

可以是模型的结构。

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

我希望这很清楚。

4

2 回答 2

3

鉴于你的例子,我会安排这样的项目:

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

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

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

于 2012-11-05T23:49:30.943 回答
0

我使用 MVC 的时间不长,但是,在我的商店中,ViewModel 是我们构建我们想要传递给视图的数据的方式,帮助我理解它的方法之一是它可以用来将两个或更多模型在特定视图中使用。

模型设置您希望对象具有的属性,在此示例中,联系人返回类型“Person”,ContactAddress 返回类型“地址”(我使用了不同的数据类型,因为我认为它是一个更清晰的示例,我希望我没有t混淆任何东西):

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

ViewModel 我们知道我们的最终视图将需要联系人数据以及他们的 ContactAddress 数据。我们可以使用 ViewModel 作为一种方式来保存两组数据并将其传递给我们的视图。

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);
}
于 2012-11-05T23:54:07.353 回答