Does HierarchicalDataTemplate.Triggers support conditional binding to ItemsSource and ItemTemplate?

The following xaml generates a compile time error: Cannot find template property "ItemsSource" on type "System.Windows.Controls.ContentPresenter"

    <HierarchicalDataTemplate x:Key="tvTemplate">
        <TextBlock Text="{Binding Path=Name}"/>
        <HierarchicalDataTemplate.Triggers>
            <DataTrigger Binding="{Binding HasSubCat1}" Value="True">
                <Setter Property="ItemsSource" Value="{Binding SubCategories1}" />
                <Setter Property="ItemTemplate" Value="{Binding subCat1Template}" />
            </DataTrigger>
            <DataTrigger Binding="{Binding HasSubCat1}" Value="False">
                <Setter Property="ItemsSource" Value="{Binding SubCategories2}" />
                <Setter Property="ItemTemplate" Value="{Binding subCat2Template}" />
            </DataTrigger>
        </HierarchicalDataTemplate.Triggers>
    </HierarchicalDataTemplate>
</UserControl.Resources>

      

Basically, I have data that when rendered will be two levels or three levels deep ... the type of data objects will differ depending on whether it is intended to be part of a level 2 or 3 branch. That's why I you need to conditionally set the source of the template and elements. It can be done

+3


source to share


1 answer


Not really sure about your description exactly what your data looks like, but I think you want HierarchicalDataTemplates

to DataTemplateSelector

choose between them in each element. The selector just has to switch between templates depending on some value in the data item, like what your DataTriggers do:

public class CategoryTemplateSelector : DataTemplateSelector
{
    public DataTemplate Cat1Template { get; set; }
    public DataTemplate Cat2Template { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        return ((CategoryBase)item).HasSubCat1 ? Cat1Template : Cat2Template;
    }
}

      

Then you need 2 simple templates, each with a different binding ItemsSource

:



<HierarchicalDataTemplate x:Key="tvTemplate1" ItemsSource="{Binding SubCategories1}">
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="tvTemplate2" ItemsSource="{Binding SubCategories2}">
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>

      

And then on TreeView

instead of setting, ItemTemplate

use a selector:

<TreeView.ItemTemplateSelector>
    <local:CategoryTemplateSelector Cat1Template="{StaticResource tvTemplate1}" Cat2Template="{StaticResource tvTemplate2}"/>
</TreeView.ItemTemplateSelector>

      

+4


source







All Articles