2

I have a problem showing items of a special type in a DataGrid. I created a minimal example.

Let´s say I have an abstract BaseClass and many inheriting ChildClasses:

public abstract class BaseClass
{
    public int BaseProperty { get; set; }
}

//Many ChildClasses possible
public class ChildClass : BaseClass
{
    public int ChildProperty { get; set; }
}

My DataContext contains a collection of all items:

public ObservableCollection<BaseClass> Items { get; set; }

Now I want to show all items of the collection of a special type in a GridView. To filter out a type, I created a CollectionViewSource:

<CollectionViewSource Source="{Binding Items}" x:Key="ChildClasses" Filter="ChildClassesFilter"/>

And here is the resulting GridView using the CollectionViewSource:

<DataGrid ItemsSource="{Binding ChildClasses}"/>

Now my problem: In the DataGrid only the BaseProperty is shown (AutoGenerateColumns) automatically. How can I force WPF to show also the ChildProperty without describing the property in the XAML?

Or is there a different approach to show only the items of a special type in my GridView?

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49

1 Answers1

0

What you want to do can't work, because the properties shown in data grid columns have to be present in every entry of the Items collection. Only the properties declared in your BaseClass are guaranteed to be present in every instance that is put into the Items collection.

That is the reason why AutoGenerateColumns does not create columns of the child instances. You have several options how to fix that:

  1. Change your collection to take only instances of your ChildClass
  2. Implement your ChildProperty in your BaseClass and have the ChildClass overload it
  3. Use a Wrapper Objekt that contains all properties you want to expose and have it handle fetching the correct values and properties based on the type of the wrapped object.
  4. You could use dynamic objects and type descriptors to fetch the properties of every object. There is a example here how that could work.
  5. You declare the columns in XAML.
Community
  • 1
  • 1
Nitram
  • 6,486
  • 2
  • 21
  • 32