C# 将DataGrid列绑定到列表
我正在开发一个基于MVVM的WPF应用程序。我想将字符串列表绑定到列标题,即,如果列表包含“abc”、“xyz”、“pqr”,那么我的C# 将DataGrid列绑定到列表,c#,wpf,mvvm,datagrid,C#,Wpf,Mvvm,Datagrid,我正在开发一个基于MVVM的WPF应用程序。我想将字符串列表绑定到列标题,即,如果列表包含“abc”、“xyz”、“pqr”,那么我的DataGrid应该有三列,标题为abc、xyz、pqr。这是我绑定datagrid的类。行存储在ObservableCollection中,其中ObservableCollection的每个元素都是构成行单元格的字符串列表 public class Resource { private ObservableCollection<string>
DataGrid
应该有三列,标题为abc、xyz、pqr。这是我绑定datagrid的类。行存储在ObservableCollection
中,其中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");
}
}
公共类资源
{
私有可观察收集列;
公共可观测收集列
{
得到
{
返回列;
}
设置
{
列=值;
}
}
私人可观测收集行;
公共可观测收集行
{
得到
{
返回行;
}
设置
{
行=值;
}
}
公共资源()
{
列表a=新列表();
a、 添加(“1”);
a、 添加(“2”);
列表b=新列表();
b、 添加(“11”);
b、 添加(“21”);
行=新的ObservableCollection();
第行。添加(a);
第行。添加(b);
Columns=新的ObservableCollection();
添加(“Hello”);
列。添加(“世界”);
}
}
我在网上搜索了很多,但找不到任何有用的例子。我确实只需要通过此方法绑定
DataGrid
。您可以通过以下两种方式之一使用DataGrid:
1) 将DataGrid的ItemsSource绑定到一组元素,这些元素公开了3个属性abc、xyz、pqr
政务司司长:
你想对列进行重新排序吗?@Markus我需要按列排序,但根据我的经验,不需要重新排序,尽管使用附加属性是可行的,但这种方法过于繁琐和限制,迫使你转向过程代码UI特定的事情,而这些事情实际上应该在XAML中完成。使用每个数据类型定义的特定XAML
DataTemplate
,而不是尝试“一刀切”的解决方案,该解决方案只适用于非常基本的纯字符串数据类型。这并不能回答问题,它不依赖于列
,因为MyDataItem
包含固定数量的属性,并且不依赖于列ObservableCollection
。
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; }
}
<DataGrid ItemsSource="{Binding DataItems}" />
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;
}
}