【问题标题】:Dynamically add data to columns in GridView将数据动态添加到 GridView 中的列
【发布时间】:2020-11-16 12:37:27
【问题描述】:

我有以下代码在 WPF GridView 控件中动态创建列,标题名称来自 string[],它存储在名为 data_orgList<string[]>

GridView gv = tabell.View as GridView;

foreach (string s in data_org.ElementAt(0))
{
   gv.Columns.Add(new GridViewColumn { Header = s });
}

有没有办法在我创建列时添加数据?我已经在添加列语句中搜索了执行此操作的方法,但找不到方法。

gv.Columns.Add(new GridViewColumn{Header = s, **statement to add data to column**});

我的数据存储在另一个List<float[]> 中,其中每个项目float[] 代表一列。我是否也必须做一些事情来处理该数据类型 (float[])?

【问题讨论】:

    标签: c# wpf listview gridview


    【解决方案1】:

    您不能将数据项直接添加到GridView 的列中。相反,您设置关联的ListViewItemsSource,在您的情况下为tabell

    tabell.ItemsSource = /* Set a binding or assign an items collection. */;
    

    然后,您将为每一列创建与数据项的相应属性的绑定,这些属性应使用DisplayMemberBinding 显示在列中。

    var gridViewColumn = new GridViewColumn
    {
       Header = s,
       DisplayMemberBinding = new Binding(/* Binding property path / name of the property. */);
    };
    

    由于每列只有一个floats 列表,因此您应该首先创建一个合适的数据项类型。 ItemsSource 需要一个包含每一列属性的项目列表,它代表一行。

    你现在要做的是:

    • 创建一个包含每列属性的行数据类型

      public class MyDataItem
      {
         public float Number { get; }
      
         // ...properties for other columns..
      }
      
    • 使用浮动列表中的数据创建这些数据项的集合。

      var myDataItemList = new List<MyDataItem>();
      // ...create data items, add your data and add the items to the list.
      
    • 将列表指定为ListView 的项目源。

      tabell.ItemsSource = myDataItemList;
      
    • 为每列添加显示成员绑定。

      var gridViewColumn = new GridViewColumn
      {
         Header = s,
         DisplayMemberBinding = new Binding(nameof(MyDataItem.Number));
      };
      

    那么它应该可以工作。不过,我建议您看看 MVVM 设计模式。

    【讨论】:

    • 非常感谢!我的问题是我不知道运行前的列数。我只知道他们是花车。因此,据我所知,创建一个基于行的类,其中每个属性代表一列是不可能的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多