Reputation: 1694
I would like to set the user defined column Header in a WPF datagrid that is bound to a database.
for displaying ServerID, EventlogID I would like to display as Server, Event Log in the column header.
I have tried these already ...
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="Server" Width="Auto" IsReadOnly="True" Binding="{Binding Path=ServerID}" />
<DataGridTextColumn Header="Event Log" Width="Auto" IsReadOnly="True" Binding="{Binding Path=EventLogID}" />
</DataGrid.Columns>
</DataGrid>
This works fine, and it changes the Column Header and the datas are also displayed.
But my problem it is displayed twice as first two column header from XAML and other two column header from the DB.
|Server|Event Log|ServerID|EventLogID|
how to overcome this replication ? Kindly help !
Upvotes: 11
Views: 7172
Reputation: 501
XAML: Add AutoGeneratingColumn="OnAutoGeneratingColumn"
event to DataGrid
evement:
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding YourItems}" AutoGenerateColumns="True" AutoGeneratingColumn="OnAutoGeneratingColumn">
Code Behind: Add event handler as following:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
switch (e.Column.Header)
{
case "ServerID":
e.Column.Header = "Server";
break;
case "EventID":
e.Column.Header = "Event";
break;
default:
e.Cancel = true;
break;
}
}
Upvotes: 0
Reputation: 16618
That's because you left the AutoGenerateColumns="True"
remove it, and there will be no more duplication.
You're currently adding the columns once, automatically, and then a second time, manually!
Upvotes: 12