I have a WPF 4.0 DataGrid that is bound to a DataTable using AutoGenerateColumns=True. The columns are dynamic, however I know there is always going to be a column named ID and I would like to hide this column. Is there a way I can do this?
views:
28answers:
2I can't speak for 4, however it was not possible in 3.5 SP1, at least without registering for an event which I wanted to avoid at all costs.
What you could do instead is change your generation code to AutoGenerateColumns=False
then just place the columns you care about within the XAML as the underlying data will all still be placed within the columns appropriately
<dg:DataGridTextColumn Header="Display" Binding="{Binding DisplayName}"/>
<dg:DataGridTextColumn Header="Host" Binding="{Binding HostName}"/>
<dg:DataGridTextColumn Header="Database" Binding="{Binding Database}"/>
<dg:DataGridTextColumn Header="Username" Binding="{Binding Username}"/>
<dg:DataGridTextColumn Header="Password" Binding="{Binding Password}"/>
This will allow you to display the only columns you care about in relation to the underlying model as well as change the Header
to display as you see fit, so you are not tied to the Property
name on the model.
in your datagrid, subscribe for the AutoGeneratingColumn event, the event args (DataGridAutoGeneratingColumnEventArgs) has the column name and a "Cancel", if the column name is ID then set Cancel = true. should do the trick.