wpfgenericsdatatemplateselector

WPF Data Template Selector based on Generic Types


I've seen a lot of examples how to use Data Template Selector to show different controls according to the x:TargetType. I want to create an items control that show a RadioButton, TextBox or TextBlock according to the class tyepe. My class could be like this:

public class MyExample<T>
{
   public string Name {get;set;}
   public Type Type => TypeOf(T)
   public T Value {get;set;}
}

I know that the Xaml can't recognize generics and I don't want to create a markup extension for supporting generics, I want to keep it simple. I don't want to create a concrete class for each type. I know that I can use a Data Trigger to set the content template according to a property (for example type name, or Type Type) but I think that should be an easier way using a Data Template Selector. Can I use the TargetType on the Type Property instead of class type?


Solution

  • Can I use the TargetType on the Type Property instead of class type?

    No.

    The obvious solution would be to create a sub-type and a corresponding DataTemplate for each type of T. The implementation for each sub-type would be a one-liner:

    public class MyExampleInt : MyExample<int> { }
    public class MyExampleString : MyExample<string> { }
    

    If you don't want to create concrete sub-types for whatever reason, you could use a DataTemplateSelector to select a template based on the type of each MyExample<T>:

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        switch (item)
        {
            case MyExample<int> i:
                return IntTemplate;
            case MyExample<string> s:
                return StringTemplate;
        }
    
        return null;
    }