首页 > 解决方案 > 绑定到 ObservableCollection 内对象的 ObservableCollection 属性

问题描述

我想在 GridView 中显示对象 DataRow 的“列”数据:

public class DataRow 
{
    public string Row { get; set; }
    public ObservableCollection<IDictionary<string, object>> Columns { get; set; }

    public DataRow(string row, ExpandoObject columnData)
    {
        this.Row = row;
        this.Columns = new ObservableCollection<IDictionary<string, object>>() { columnData as IDictionary<string,object>};
    }
}

我所有的 DataRow 对象都收集在另一个类的 ObservableCollection 中:

public class Table
{
    public string DataTableName{ get; set; }
    public ObservableCollection<DataRow> Data{ get; set; }
}

我所有的表都包含在另一个类的 ObservableCollection 中:

public class MyTables
{
   public ObservableCollection<Table> MyTables{ get; set; }
}

因此,我尝试通过以下方式进行绑定:

<ItemsControl ItemsSource="{Binding MyTables}">
   <ItemsControl.ItemTemplate>
        <DataTemplate>
             <Grid>
                  <Grid.RowDefinitions>
                        ...
                  </Grid.RowDefinitions>
                  <Grid.ColumnDefinitions>
                        ...
                  </Grid.ColumnDefinitions>

                  <Label ...Text="{Binding DataTableName}"/>

                  <telerik:RadGridView
                        ...
                        AutoGenerateColumns="True"
                        ItemsSource="{Binding Data.Columns}"/>
              </Grid>
         </DataTemplate>
     </ItemsControl.ItemTemplate>
  </ItemsControl>

我不明白为什么我不能将 GridView 的 ItemsSource 绑定到 Data.Columns- ObservableCollection。

错误信息:

BindingExpression 路径错误:在“对象”“ObservableCollection`1”(HashCode=61300126)上找不到“列”属性。BindingExpression:Path=Data.Columns; DataItem='表' (HashCode=50904493); 目标元素是'RadGridView'(名称='');目标属性是“ItemsSource”(类型“对象”)

除了仅显示数据外,表格还应支持从 Excel 复制/粘贴和编辑值。因为我事先不知道需要多少行和列,所以我使用动态 ExpandoObject,我可以在运行时添加属性,这些属性是我在数据网格中的列。

标签: c#data-bindingobservablecollection

解决方案


名为“Data”的对象是 DataRow 的 ObservableCollection。正如您收到的错误中提到的那样,该对象没有称为“列”的属性。
如果要为 Data 中的每个 DataRow 显示 Columns,则可能需要使用分层网格,在其中显示“Row”属性和 Columns 数据作为子网格。请参阅https://docs.telerik.com/devtools/wpf/controls/radgridview/getting-started/building-hierarchical-grid-view


推荐阅读