I have a .Net datatable that I am using as a source to a WPF datagrid. The problem I have is that some of the column headers in the datatable contain dots. When binding the
Magnus Montin has solved the question at Microsot WPF Forum :
AutoGeneratedColumns
are rarely useful in real-world scenarios. But you could also handle theAutoGeneratingColumn
event:
<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 + "]") };
}
Anyway, this kind of view related code certainly belongs to the view. The view model doesn't know nor care about the fact that the DataGrid control cannot display the actual data for some reason. This has to be and should be fixed in the view.
It works like a charm! My example started to work:
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"/>
Code behind:
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 + "]")
};
}
ViewModel:
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);
}
}
As you've discovered, dot notation for anything other than Binding
is problematic with WPF. What I'd recommend is to revise your headers to alias the column names with dot notation:
Col.A should be Col_A
Col.B should be Col_B
etc...
If the headers are coming from a direct SQL query, alias the sql column names in the same manner.
Going down the path of using the dot notation will just continue leading into one hackish fix to resolve the previous 'fix'. All of this can be easily resolved by just revising your naming conventions.