【问题标题】:MVVM: using commands when binding to collection of business model objectMVVM:绑定到业务模型对象集合时使用命令
【发布时间】:2013-04-17 11:58:53
【问题描述】:

我们是否应该将模型属性直接绑定到视图一直存在争议。但是大多数示例在线绑定模型属性以直接查看,例如{Binding Model.Property}

我正在创建一个简单的 WPF 应用程序,其中我有一个数据网格,每行都有一个按钮来显示一个弹出窗口。

商业模式如下:

public class DataGridItem
{
    public string Summary { get; set; }
    public string Name { get; set; }
}

viewmodel 类看起来像

public class DataGridItemViewModel : NotifyableEntity
{
    public DataGridItemViewModel()
    {
        Data = new ObservableCollection<DataGridItem>();
    }
    public string Summary { get; set; }

    public string Name { get; set; }

    public ObservableCollection<DataGridItem> ItemsList { get; set; }

}

DataGridItemsSource 属性绑定到viewmodelItemsList 属性。现在在这种情况下,如果我将Command 绑定到datagrid 中的ViewLog 按钮,那么它会在业务模型类中查找命令。 如何在viewmodel 本身中定义命令,而无需在viewmodel 中编写代理/包装器属性?

【问题讨论】:

  • 这正是我不喜欢绑定到(业务)模型的原因。在不知不觉中,您将向 ViewModel 添加属性,并且您将获得许多奇怪的绑定来绑定到 Model 和 ViewModel

标签: wpf mvvm collections command


【解决方案1】:

我同意为子集合创建 ViewModel 是一种痛苦和抽象诱导仪式的练习,但我认为您不需要这些视图模型来处理命令。您可以为 Button 提供不同的 DataContext,以便它绑定到您希望的任何视图模型(或模型):

....
<ItemsControl ItemsSource="{Binding ItemsList}">
  <ItemsControl.ItemTemplate>
    <DataTemplate DataType="{x:Type DataGridItemViewModel}">
      <Button Command="{Binding MyCommand}" DataContext="{Binding DataGridItemViewModel}"/>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
...

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2012-02-07
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多