Ryan Searle Ryan Searle - 1 year ago 75
C# Question

Hide a Column from a DataGrid when the ItemSource is an Observable Collection

I have a

where the
is an Observable Collection bound using
archetype. I would like to not show the ID property of the class displayed in my
however I still need the property to exist.

My Code:


<DataGrid ItemsSource="{Binding MyData}" IsReadOnly="True" Grid.ColumnSpan="2" Name="dtSearch" Margin="10" ColumnWidth="*" Grid.Row="2"/>

View Model

private ObservableCollection<MyDataClass> myData;
public ObservableCollection<MyDataClass> MyData
get { return myData; }
myData= value;

Observable Class

public partial class MyDataClass
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Type { get; set; }

Is there an attribute I can give my ID property to hide it from the

Do I need to create another class for visible properties?

Some guidance would be great!

Answer Source

This issue will happen regardless of whether the data resides in an ObservableCollection or not.

To correct this one must set the grid to not auto generate the columns. That is done by setting the AutoGenerateColumns=False and then in the xaml specify the columns desired.

<DataGrid ItemsSource="{Binding  MyData}" AutoGenerateColumns="False" >
      <DataGridTextColumn Header="The Code"
                      Binding="{Binding Code}"/>
      <DataGridTextColumn Header="The Name"
                      Binding="{Binding Name}"/>
      <DataGridTextColumn Header="The Type"
                      Binding="{Binding Type}"/>

Check out more column options in the documentation for the DataGrid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download