我有一个简单的控件,其中包含一个 DataGrid,其中 ItemsSource 绑定到 DataTable。当我填充 DataTable 时,我可以看到 DataGrid 中添加了行,但没有显示任何数据。我没有为此 DataGrid 使用任何特殊样式(采用默认样式),唯一的设置是将 AutoGenerateColumn 设置为 True。
在 XAML 中
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding TableResult}"/>
在视图模型中
private DataTable tableResult = new DataTable();
public DataTable TableResult
{
get { return tableResult; }
set { tableResult = value; OnPropertyChanged("TableResult"); }
}
private void FillTable()
{
DataColumn c = new DataColumn();
c.ColumnName = "Col1";
this.TableResult.Columns.Add(c);
c = new DataColumn();
c.ColumnName = "Col2";
this.TableResult.Columns.Add(c);
DataRow row1 = this.TableResult.NewRow();
row1["Col1"] = "Blue";
row1["Col2"] = "12";;
this.TableResult.Rows.Add(row1);
DataRow row2 = this.TableResult.NewRow();
row2["Col1"] = "Red";
row2["Col2"] = "18";
this.TableResult.Rows.Add(row2);
DataRow row3 = this.TableResult.NewRow();
row3["Col1"] = "Yellow";
row3["Col2"] = "27";
this.TableResult.Rows.Add(row3);
}
填充 DataGrid 数据的工作示例:
public MyViewModel()//constructor of MyViewModel
{
FillMyDataGrid();
}
private DataTable employeeDataTable;
public DataTable EmployeeDataTable
{
get { return employeeDataTable; }
set
{
employeeDataTable = value;
OnPropertyChanged("EmployeeDataTable");
}
}
public FillMyDataGrid()
{
var _ds = new DataSet("Test");
employeeDataTable = new DataTable();
employeeDataTable = _ds.Tables.Add("DT");
for (int i = 0; i < 50; i++)
{
//employeeDataTable.Columns.Add(i.ToString() + ".");
employeeDataTable.Columns.Add(i.ToString());
}
for (int i = 0; i < 2; i++)
{
var theRow = employeeDataTable.NewRow();
for (int j = 0; j < 50; j++)
{
theRow[j] = "a";
}
employeeDataTable.Rows.Add(theRow);
}
}
XAML 代码:
<DataGrid ItemsSource="{Binding EmployeeDataTable}"/>
Update:
我已经测试了你的示例并且它工作正常,但是你应该调用你的方法FillTable()
在构造函数中填充DataTable
。例如:
public class YourViewModel
{
public YourViewModel()
{
FillTable();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)