WPF TreeView如何为TreeViewItem的IsSelected创建触发器

时间:2016-07-17 08:40:49

标签: c# wpf treeview

以下代码是树视图:

   <TreeView BorderThickness="1,1,1,1" BorderBrush="#ffcccccc"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  
              ItemTemplate="{StaticResource itemTypeTreeViewTemplate}"
              ItemsSource="{Binding ItemTypes}"
              ItemContainerStyle="{StaticResource treeViewItemStyle}"/>

我设置itemTemplate来设置项目的绑定。然后设置ItemContainerStyle以更改IsSelected样式:

  <Style x:Key="treeViewItemStyle" TargetType="TreeViewItem">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="LightBlue" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <HierarchicalDataTemplate x:Key="itemTypeTreeViewTemplate" 
                              ItemsSource="{Binding Child}">
                <DockPanel Margin="0,5,0,5">
                    <Button VerticalAlignment="Center"
                        x:Name="btn1" Width="25"
                        Visibility="{Binding Path=IsMouseOver,RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BooleanToVisibilityConverter }}"
                        Content="U" DockPanel.Dock="Right" cal:Message.Attach="[Event Click] = [Action EditItemType($dataContext)]" 
                        Style="{StaticResource ButtonStyle1}" />
                    <TextBlock Margin="0,2,0,2" VerticalAlignment="Center" Text="{Binding ItemTypeName}" Foreground="#FF2e8bcc" FontSize="10" FontFamily="微软雅黑" />
                </DockPanel>    
    </HierarchicalDataTemplate>

但isSelected风格不起作用。有人找到钥匙??

1 个答案:

答案 0 :(得分:0)

您应该覆盖突出显示状态的颜色键,而不是使用样式触发器。这是代码:

<Style x:Key="treeViewItemStyle" TargetType="TreeViewItem">
    <!--<Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="LightBlue" />
        </Trigger>
    </Style.Triggers>--><!--Remove Style.Trigger block-->
    <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                   Color="LightBlue"/>
        </Style.Resources>
</Style>

希望这会有所帮助。此控件的其他键是:

  • HighlightBrushKey - 专注背景。 (专注于 选择的)
  • HighlightTextBrushKey - 专注前景。
  • InactiveSelectionHighlightBrushKey - 正常背景。
  • InactiveSelectionHighlightTextBrushKey - 正常前景。