0

I have an object something like this:

public class Item 
{
  public string Name;
  public int Id;
  public int Quantity;
  public decimal Volume;
  public decimal Cost;
}

I'm wanting to create a reusable user control which would take a list of these objects and display them in a datagrid. The trick is that I want to specify which of the properties are shown in the datagrid for each instance of the control. Unfortunately my WPF skills are not up to the tasks and I don't want to create a specific control for each combination that I will want to use, as that feels like a lot of work for very similar code items. Any help to pointers of how to accomplish this would be greatly appreciated.

kw1jybo
  • 142
  • 1
  • 8

1 Answers1

0

You can use the Columns property of your datagrid to interact with the columns and hide the columns you don't want.

datagrid.Columns.RemoveAt(IndexOftheColumn);

or if you named your columns

datagrid.Columns.RemoveAll(x => x.Name = "column name");

or if it is possible that you will need to column later

datagrid.Columns[IndexOftheColumn].Visibility = Visibility.Collapsed;

It is also possible to do this with pure Xaml with bindings but since you are new to Wpf I would suggest doing it in the code behind (the .cs of your Wpf control) first.

As for selecting which columns to hide you can pass a list of names for the columns you want to remove in the constructor of the control or with a binding. There are a lot of ways to do it.

Or you could do the opposite and add columns dynamically based on your needs.

Note that this question has been asked before

Hastaroth
  • 41
  • 1
  • 2
  • 7