This question is related to the accepted answer in my question: Dynamic content in DataGrid or GridView CellTemplate
I have a collection of different datatypes to the ItemSource of the DataGrid, and depending on the datatype of the current index in the DataSignalModel
collection, the corresponding DataType is to be used.
This the solution that helped me in the linked question:
As you store a data type member instead of creating two distinct model types, you will have to create a custom DataTemplateSelector for selecting the data template depending on DataType.
public class DataSignalModelTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (!(item is SignalDisplayModel dataSignalModel) || !(container is FrameworkElement containerFrameworkElement))
return null;
switch (dataSignalModel.DataType)
{
case DataType.Bool:
return FindDataTemplate(containerFrameworkElement, "DataSignalModelBoolTemplate");
case DataType.Int:
case DataType.Float:
return FindDataTemplate(containerFrameworkElement, "DataSignalModelNumericTemplate");
default:
throw new ArgumentOutOfRangeException();
}
}
private static DataTemplate FindDataTemplate(FrameworkElement frameworkElement, string key)
{
return (DataTemplate)frameworkElement.FindResource(key);
}
}
And I want to follow the advice below.
A note on data types: You keep a member DataType in your DataSignalModel to determine its type. Usually you would create specialized types for each data and not a one-for-all mode
So when I change my design to have an interface or base class and concrete implementation of the different types, how do I adapt my current solution to use the different DataTemplate's?
- Get rid of the custom DataTemplateSelector and somehow bind the different DataTemplates to the corresponding IDataSignalModel implementations?
- Adapt the custom DataTemplateSelector to return the DataTemplate on item type?
- Or maybe a different approach?
ObservableCollection<object>
used as ItemsSource. Then have DataTemplates with appropriate DataTypes for all types you need. – Clemens