wpf DataTable 作为 DataGrid.ItemsSource
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14942105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataTable as DataGrid.ItemsSource
提问by WiiMaxx
hi i want to bind a DataTablewith multiple columns to an DataGridin codebehind
嗨,我想将DataTable多列绑定到代码DataGrid隐藏中
var dt = new DataTable();
dt.Columns.Add(new DataColumn("1"));
dt.Columns.Add(new DataColumn("2"));
dt.Columns.Add(new DataColumn("3"));
dt.Rows.Add(ff.Mo);
dt.Rows.Add(ff.Di);
dt.Rows.Add(ff.Mi);
dt.Rows.Add(ff.Do);
dt.Rows.Add(ff.Fr);
dt.Rows.Add(ff.Sa);
dt.Rows.Add(ff.So);
// ff is a object that contains List<myCellObj>
DataGrid DGrid = new DataGrid();
for (int i = 0; i < 3; i++)
{
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.HeaderTemplate = HeaderDt;
templateColumn.CellTemplate = ItemDt; //specified DataTemplate for myCellObj
DGrid.Columns.Add(templateColumn);
}
now how do i set my dtas ItemsSource, Datacontextor what ever to get it in to my Viewalso if you could provide me a way to bind directly to my Object ff
现在我如何设置我的dtas ItemsSource,Datacontext或者View如果你能为我提供一种直接绑定到我的方法,或者将它放入我的Object ff
anything that could help is greatly appreciated
任何可以提供帮助的东西都非常感谢
回答by Lee Harrison
Assuming you're in WPF simply say:
假设您在 WPF 中,只需说:
DGrid.ItemsSource = dt.AsDataView();
No need to manually setup your columns on your DataGrid, assigning the DataTable will set these up for you.
无需在 DataGrid 上手动设置列,分配 DataTable 将为您设置这些列。

