Magnus Montin在 Microsot WPF 论坛上解决了这个问题:
AutoGeneratedColumns
在现实世界的场景中很少有用。但您也可以处理该AutoGeneratingColumn
事件:
<DataGrid Name="dataGrid" AutoGenerateColumns="True" AutoGeneratingColumn="dataGrid_AutoGeneratingColumn" />
private void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column = new DataGridTextColumn() { Header = e.PropertyName, Binding = new Binding("[" + e.PropertyName + "]") };
}
反正这种视图相关的代码肯定是属于视图的。视图模型不知道也不关心 DataGrid 控件由于某种原因无法显示实际数据的事实。这必须并且应该在视图中修复。
它就像一个魅力!我的示例开始起作用:
XAML:
<DataGrid ColumnWidth="35" ItemsSource="{Binding EmployeeDataTable,
IsAsync=True}" VirtualizingStackPanel.IsVirtualizing="true"
EnableRowVirtualization="True" EnableColumnVirtualization="True"
MaxWidth="2560" MaxHeight="1600"
VirtualizingStackPanel.VirtualizationMode="Recycling"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"/>
后面的代码:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column = new DataGridTextColumn() {
Header = e.PropertyName,
SortMemberPath = e.PropertyName, //To allow for sorting on a column
Binding = new Binding("[" + e.PropertyName + "]")
};
}
视图模型:
private DataTable employeeDataTable;
public DataTable EmployeeDataTable
{
get { return employeeDataTable; }
set
{
employeeDataTable = value;
OnPropertyChanged("EmployeeDataTable");
}
}
private void PopulateDataTable()
{
var _ds = new DataSet("Test");
employeeDataTable = new DataTable();
employeeDataTable = _ds.Tables.Add("DT");
for (int i = 0; i < 800; i++)
{
if(i%2==0)
employeeDataTable.Columns.Add(i.ToString() + ".");
else
employeeDataTable.Columns.Add(i.ToString() + "/");
}
for (int i = 0; i < 2; i++)
{
var theRow = employeeDataTable.NewRow();
for (int j = 0; j < 800; j++)
{
if (j % 2 == 0)
{
//theRow[j] = j.ToString();
theRow[j] = "a";
}
else
theRow[j] = CreateDoubleValue(j).ToString();
}
employeeDataTable.Rows.Add(theRow);
}
}