【问题标题】:Binding to property of collection elements绑定到集合元素的属性
【发布时间】:2013-08-27 16:02:42
【问题描述】:

我在我的 WPF 应用程序中使用 MVVM 模式。 我的 ViewModel 中有 ObservableCollection 记录。

public enum RecordState
{
    NotChanged,
    Changed,
    Added,
    Deleted,
    AlreadyExist
}
public class Record
{
    public string FirstId { get; set; }
    public RecordState State { get; set; }
    public string CurrentId
    {
        get { return GetIdFromInstance(Instance); }
    }
    public MyStronglyTypedClass Instance { get; set; }
}

public class MyViewModel
{
    public ObservableCollection<Record> Records;
    // other code
}

在视图中我有 DataGrid。

<DataGrid ItemsSource="{Binding }" //>

我必须在 ItemsSource="{Binding /* here */}" 中写什么(如果可能的话),以便 Datagrid Items 更改为

Records[0].Instance
Records[1].Instance
Records[2].Instance
...
Records[Records.Count-1].Instance

【问题讨论】:

  • 为什么不绑定到集合? {绑定记录}
  • 因为 Datagrid 是我的 UserControl 的一部分,并且我在我的代码周围使用带有 MyStronglyTypedClass 的 UserControl(和 DataGrid)。 MyStronglyTypedClass 有许多属性和元素的集合。 DataGrid 的列是创建 1) 动态的(这里是 idea) 2) 列绑定到代码中的 元素 3) 单元格数据模板是根据元素的类型动态选择的

标签: wpf data-binding mvvm datagrid


【解决方案1】:

{Binding} 表示您的 ItemsSource 是该 DataGrid 的 DataContext(可能继承自祖先元素)。 您应该做的是将您的顶级元素(Window、UserControl 等)的 DataContext 设置为您的 ViewModel 类。 然后按照 Gary 的建议:

<DataGrid ItemsSource="{Binding Records}">

您提供的关于动态元素的链接在这方面也是如此,它添加了更复杂的元素绑定和 DataTemplates。

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 2014-07-17
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多