Ryan Searle Ryan Searle - 1 month ago 12
C# Question

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

I have a

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

My Code:

XAML

<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; }
set
{
myData= value;
RaisePropertyChanged("MyData");
}
}


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
DataGrid
?

Do I need to create another class for visible properties?

Some guidance would be great!

Answer

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" >
   <DataGrid.Columns>
      <DataGridTextColumn Header="The Code"
                      Binding="{Binding Code}"/>
      <DataGridTextColumn Header="The Name"
                      Binding="{Binding Name}"/>
      <DataGridTextColumn Header="The Type"
                      Binding="{Binding Type}"/>
   </DataGrid.Columns>
  </DataGrid>

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

Comments