【问题标题】:DataBinding DataGrid to Custom Data StructureDataBinding DataGrid 到自定义数据结构
【发布时间】:2012-09-25 23:27:16
【问题描述】:

所以我在涉足 Winforms 几年后才加入 WPF 俱乐部。我绝对喜欢 WPF 中的数据绑定,但我在使用 DataGrid 时遇到了问题。

我有一个高度自定义的数据结构,它存储来自 SQL 查询的结果,我想继续在 WPF 中使用它。我已经看到了绑定到对象列表的示例,但没有看到像 SQL 查询这样的动态。

是否有一些接口可以让我的数据结构实现,以便DataGrid 可以获取必要的信息,例如行数和列数、标题和数据?

【问题讨论】:

    标签: wpf data-binding datagrid


    【解决方案1】:

    我的目标是绑定到类似于DataTable 的自定义结构,允许DataGrid“发现”关于我的结构的信息。

    简短的回答是实现以下接口:

    IList IEnumerable ITypedList

    以及从CustomTypeDescriptor 继承(或实现ICustomTypeDescriptor

    This Question 在处理最具挑战性的CustomTypeDescriptor 问题上提供了很大帮助。

    我的枚举对象是一个简单的对象,它存储了对主表的引用,因此它可以询问特定行和列的值是什么。

    public AgilityTableRow(AgilityTableBase table, int rowIndex)
        {
            _table = table;
            _rowIndex = rowIndex;
        }
    
        public object this[int columnIndex]
        {
            get 
            {
                return _table[columnIndex, _rowIndex]; 
            }
        }
    
        public object this[string columnName]
        {
    
            get 
            {
                return _table[_table.GetFieldIndex(columnName), _rowIndex]; 
            }
        }
    

    注意:这个类需要实现ICustomTypeDescriptor,并且可以简单地将调用转发到表来获取属性:

    public PropertyDescriptorCollection GetProperties()
        {
            return _table.GetProperties();
        }
    

    【讨论】:

      【解决方案2】:

      这些项目应该实现 INotifyPropertyChanged 并且你应该把它们放在一个 ObservableCollection 中,这样网格就会收到有关更改的通知。

      如果您将 AutoGenerateColumns 设置为 true,则 Grid 将自动为您的模型的每个属性创建一个列。

      如果您只有“原始”数据而没有模型类,那么我认为您必须手动创建列。 WPF 绑定非常灵活,还可以绑定到索引属性/数组等。也许这可以帮助您处理“动态”数据。

      <TextBlock Text="{Binding myArray[0]}" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        • 1970-01-01
        • 2021-10-01
        • 2015-12-18
        • 2021-02-22
        • 2013-08-30
        相关资源
        最近更新 更多