Search code examples
wpfxamltreeviewdatatriggerhierarchicaldatatemplate

DataTrigger in Style in HierarchicalDataTemplate not working -- TreeView


I have a DataTrigger to set a TextBox's Background based on a bound property.
Here's a streamlined version of the xaml:

<TreeView  >
<TreeViewItem Header="Things" >
    <TreeViewItem.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsDirty}" Value="True">
                    <Setter Property="Background" Value="LightGray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
        <HierarchicalDataTemplate DataType="{x:Type local:Type1}" ItemsSource="{Binding Children, Mode=OneWay}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" Margin="6,0,6,0" />
                <TextBlock Text="{Binding IsDirty}" Margin="6,0,6,0" />
                <i:Interaction.Behaviors>
                    <dragDrop:FrameworkElementDropBehavior DragEffect="Move"  />
                </i:Interaction.Behaviors>
            </StackPanel>
        </HierarchicalDataTemplate>
    </TreeViewItem.Resources>
</TreeViewItem>

I added a TextBlock to display the value of the IsDirty property; when that is true, the Background remains unchanged.
I have tried moving the Style to the HierarchicalDataTemplate.Resources, but that made no difference.
What am I overlooking?
Thanks --


Solution

  • That's because implicit styles targeting types not derived from Control do not cross the template boundary, i.e. are not applied inside templates unless they're defined within that template's scope. Here's a good post explaining how it works and why does it work this way.

    In order to cross the template boundary, you should use a type deriving from Control (e.g. a Label) instead of a TextBlock and define implicit style targeting that type.

    Otherwise, you could put your style in scope of the template in question by moving it into the template's resources dictionary:

    <HierarchicalDataTemplate (...)>
        <HierarchicalDataTemplate.Resources>
            <Style TargetType="{x:Type TextBlock}">
                (...)
            </Style>
        </HierarchicalDataTemplate.Resources>
        (...)
    </HierarchicalDataTemplate>