I am looking for a way to display data in a DataGrid
from types that are unknown at compile-time.
I have the following base class
public abstract class Entity
{
// Some implementation of methods ...
}
In run-time, I load a plug-in DLL and use reflection to get a list of all the types derived from Entity
. For example:
public class A : Entity
{
public LocalAddress Address{ get; set; }
}
public class B : Entity
{
public Vendor Vendor { get; set; }
public string Name { get; set; }
}
Then I retreive a list of their instances from DB
public IEnumerable<Entity> Entities { get; set; } // A list of instances of type A for example
Entities
is the DataGrid's ItemsSource
, But what's the best way I can bind the properties to the DataGrid
?
Since the properties can be complex, I also need to be able to bind to a specific path, for example Address.HomeNum
...
I only need to show a one grid of a type's instances at a time. The complete scenario is this:
Entity
from the plug-in DLL through reflectionA
and B
A
, I get a list of A
instances from DB - so far so good.A
's instances in a DataGrid
.B
), I get a list of B
's instances from DB and need to display those in the grid and so on ... The plug-in DLL is a class library with no xamls (also my users are the ones making this plug-ins and I don't want them to have to write DataTemplate
s for their entities.
I also can't make predifned DataTemplate
s as I don't know the types I'll need to display until run-time. Each type can have different types and amount of properties. All I know in complie-time is that they all derived from Entity
.
A DataGrid
seems inappropriate in this case. If your list was bound to two separate entities, it would break badly.
A better option would potentially be to use some other ItemsControl
and set up a DataTemplate
for each type of Entity
. This would allow you to build custom editors per entity, and have a "list" of them to edit.
If you know the entities will always be of a single type, I'd instead build the collection of that specific type, and bind to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With