.NET Framework Developer Center > .NET Framework Forums > Windows Presentation Foundation (WPF) > Why do TargetType based Styles not work on custom template based controls?

Answered Why do TargetType based Styles not work on custom template based controls?

  • Friday, July 31, 2009 1:28 PM
     
     
    Style triggers are very handy and make our life very simple with WPF. However I am not able to utilize them when I have custom templates for controls.

    For example this simple style in which I want All the TextBlock occurrences in my UserControl to collapse when they don't have any Text(null/empty) so that they do not occupy space in with in DataTemplate.

            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <Trigger Property="Text" Value="">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

    This would work if my UserControl has simple elements like a series of TextBlocks and some other controls. But say, if I have a TreeView and I a ItemTemplateSelector to display TreeViewItem differently with various HierarchicalDataTemplate. For example one of them being this...

                <HierarchicalDataTemplate DataType="XYZ" ItemsSource ="{Binding}">
                    <Grid x:Uid="Grid_7" Width="Auto" Height="Auto">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                       
                        <Image ... Grid.Column="0" Grid.Row="0" Margin="5,0,0,0"/>
                        <TextBlock ... Grid.Column="1" Grid.Row="0" Padding="5,0,0,0"/>
                        <TextBlock ... Grid.Column="2" Grid.Row="0" Foreground="Blue"Padding="5,0,0,0"/>
                        <TextBlock ... Grid.Column="3" Grid.Row="0" Foreground="Red"Padding="5,0,0,0"/>                  
                    </Grid>
                </HierarchicalDataTemplate>

    Now even if I add the style above under <TreeView.Resources> its never get applied. TextBlocks which have their Text as null/empty still occupy the space in the HierarchicalDataTemplat.

    Can someone tell me, why doesn't the style gets applied to these HierarchicalDataTemplates? Is it because of design limitations? Or I am using it incorrectly?

    Any help on this would be appreciated, thank you!

Answers

All Replies