gpt4 book ai didi

c# - 将 DataGrid 列绑定(bind)到列表

转载 作者:行者123 更新时间:2023-11-30 22:05:27 25 4
gpt4 key购买 nike

我正在开发基于 MVVM 的 WPF 应用程序。我想将字符串列表绑定(bind)到列标题,即,如果列表包含“abc”、“xyz”、“pqr”,那么我的 DataGrid应该有标题为 abc、xyz、pqr 的三列。这是我绑定(bind)数据网格的类。这些行存储在 ObservableCollection<List<string>>ObservableCollection 的每个元素在哪里是一个字符串列表,它构成了行的单元格。

public class Resource
{
private ObservableCollection<string> columns;
public ObservableCollection<string> Columns
{
get
{
return columns;
}
set
{
columns = value;
}

}

private ObservableCollection<List<string>> row;
public ObservableCollection<List<string>> Row
{
get
{
return row;
}
set
{
row = value;
}
}

public Resource()
{
List<string> a = new List<string>();
a.Add("1");
a.Add("2");
List<string> b = new List<string>();
b.Add("11");
b.Add("21");
Row = new ObservableCollection<List<string>>();
Row.Add(a);
Row.Add(b);

Columns = new ObservableCollection<string>();
Columns.Add("Hello");
Columns.Add("World");
}
}

我在 Internet 上搜索了很多,但找不到任何有工作示例的内容。我真的需要绑定(bind) DataGrid仅通过此方法。

最佳答案

您可以通过以下两种方式之一使用 DataGrid:

1) 将 DataGrid 的 ItemsSource 绑定(bind)到一组元素,这些元素公开 3 个属性 abc、xyz、pqr。

CS:

    public List<MyDataItem> DataItems 
{
get
{
List<MyDataItem> items = new List<MyDataItem>(5);

for (int i = 0; i < 5; i++)
{
items.Add(new MyDataItem { abc = abc[i], qrt = qrt[i], xyz = xyz[i] });
}

return items;
}
}

int[] abc = new int[5] { 1, 2, 3, 4, 5 };
int[] qrt = new int[5] { 6,7,8,9,10 };
int[] xyz = new int[5] { 11,12,13,14,15};


public event PropertyChangedEventHandler PropertyChanged = delegate { };

}

public class MyDataItem
{
public int abc { get; set; }
public int qrt { get; set; }
public int xyz { get; set; }
}

XAML:

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

2) 创建一个 DataTable 对象并将其绑定(bind)到您的 ItemsSource。

 public DataTable DataTable
{
get
{
DataTable table = new DataTable();

table.Columns.Add("abc");
table.Columns.Add("qrt");
table.Columns.Add("xyz");

table.Rows.Add(1, 6, 11);
table.Rows.Add(2, 7, 12);
table.Rows.Add(3, 8, 13);
table.Rows.Add(4, 9, 14);
table.Rows.Add(5, 10, 15);

return table;
}
}

关于c# - 将 DataGrid 列绑定(bind)到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24371627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com