Reputation: 890
I am trying to fill a DataGrid with a List<>
of multiple objects. These objects all inherent from a baseclass. I am successful in showing the columns and rows in the DataGrid, however I only see the properties of the base class and not the properties of the child class.
Unfortunately I could not find much helpful information while searching the web. But I am still new to WPF and C# so maybe that's the problem...
How can I get the DataGrid to show all of the properties, from both the base and child class?
EDIT:
I have a few classes(say A, B, C) that inherit from the BaseClass and I have a list of the type List<BaseClass>
which house multiple objects of multiple types. I need to show all the different child classes in my DataGrid.
Upvotes: 5
Views: 3594
Reputation: 1584
I think you can bind your DataGridColumn which belongs to child classes.
object name of child class.property name of corresponding child class
Upvotes: 0
Reputation: 35146
<DataGrid ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Prop1}" />
<DataGridTextColumn Binding="{Binding Prop2}" />
</DataGrid.Columns>
</DataGrid>
class Base
{
}
class Derived1: Base
{
public string Prop1 { get; set; }
}
class Derived2: Base
{
public string Prop2 { get; set; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new List<Base>()
{
new Derived1(){Prop1 = "Hello"},
new Derived2() {Prop2 = "World"}
};
}
This works for me. I see Hello in first row and World in second.
Upvotes: 3
Reputation: 36753
Try using a List<ChildClass>
instead of a List<BaseClass>
.
Upvotes: 0
Reputation: 1063754
What is the T
in your List<T>
? The type metadata is inferred from that (in winforms binding, at least; so I assume this applies to WPF too). So if you have a List<BaseClass>
then only the properties of BaseClass
will be shown. Try using a List<DerivedClass>
instead.
Upvotes: 0