0

I have a list of objects that is being used as the source for a DataGrid. This list of objects is a base class type, of which there are 2 or more inherited types. I am trying to bind to properties of the base class to display as values in the columns of the DataGrid. The subclasses have different properties available to them which I would like to be able to display, so my question is, does XAML have a way to dynamically change the value of a binding based on the type that is being pointed to? I have thought about potentially doing this with a converter, but if I understand correctly, then I would have to write a different converter for each subclass property that I need to bind to. Any advice or suggestions are appreciated. Thanks

KSF
  • 370
  • 1
  • 4
  • 21

3 Answers3

0

This is probably possible, with attributes and some reflection you could mark the properties that should go in the various columns and then auto-generate those. You could also create a sparse grid, with columns for all possible properties; this should also be possible via reflection and does not require any additional metadata.

(You can auto-create the columns based on the items using an attached property (like this) if the native DataGrid event is not sufficient for this.)

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400
0

You can define multiple DataTemplates and specify the intended type through the DataType property. The correct template will be selected depending on the type of the bound object.

https://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype(v=vs.110).aspx

Drunken Code Monkey
  • 1,796
  • 1
  • 14
  • 18
  • This would be the preferred way to do it, if this wasn't about a DataGrid which has columns. – H.B. Jul 06 '16 at 20:44
  • Well that just means the datagrid is not really the control you need. You can make something pretty great looking easily with just a ListBox and templates. Each "row" will show up as it should for the bound type. – Drunken Code Monkey Jul 06 '16 at 20:47
0

The means to achieve this would be a CellTemplateSelector. See this link.

Community
  • 1
  • 1
Eyal Perry
  • 2,255
  • 18
  • 26