7H3LaughingMan
7H3LaughingMan

Reputation: 372

C# WPF x:Type Markup that includes classes that inherit a class

I am working one some custom templates for a TreeView using HierarchicalDataTemplate. However, I am having issues getting it to work with a broad range of classes that inherit from a root class. It appears that the X:Type is very specific and won't trigger on classes the inherit from the class given. Below is some further information to help describe it.

  1. I have a root class called Event that has 50+ other classes that inherit it and extend of it.
  2. When I use the following DataType="{x:Type events:Event} , it will only work if the object is just the base class.

I would prefer not have 50+ HierarchicalDataTemplates in my XAML file, so is there any method that would make it work?

Upvotes: 2

Views: 324

Answers (1)

max
max

Reputation: 34427

It's not really the {x:Type } fault, it is just the way DataTemplate is resolved from resources. Consider using custom DataTemplateSelector. Quick example:

class ItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate EventTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if(item is Event)
        {
            return EventTemplate;
        }
        // TODO: templates for other types
        return null;
    }
}

Data template definition:

<FrameworkElement.Resources>
    <local:ItemTemplateSelector x:Key="ItemTemplateSelector">
        <local:ItemTemplateSelector.EventTemplate>
            <!-- template for event -->
            <HierarchicalDataTemplate>
                <TextBlock Text="Event" />
            </HierarchicalDataTemplate>
        </local:ItemTemplateSelector.EventTemplate>
    </local:ItemTemplateSelector>
</FrameworkElement.Resources>

Usage:

<TreeView ItemTemplateSelector="{StaticResource ItemTemplateSelector}">
</TreeView>

Upvotes: 3

Related Questions