我找到了一个(有点老套)但轻量级的解决方案来解决这个问题。我看到这个问题已经很老了,但尽管如此,我会在这里发布解决方案供其他人查找。
在我的 TreeView 中,我覆盖了用于在 TreeViewItem 选择更改时设置背景的两个画笔。我还创建了画笔的副本,以便稍后在我的数据模板中恢复它们:
<TreeView ItemsSource="{Binding Path=SomeDataSource}">
<TreeView.Resources>
<SolidColorBrush x:Key="_CustomHighlightBrushKey" Color="{Binding Source={StaticResource {x:Static SystemColors.HighlightBrushKey}}, Path=Color}" />
<SolidColorBrush x:Key="_CustomControlBrushKey" Color="{Binding Source={StaticResource {x:Static SystemColors.ControlBrushKey}}, Path=Color}" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
</TreeView.Resources>
</TreeView>
请注意,我无法使其与 DynamicResource 绑定一起使用,因此此解决方案可能不适用于主题更改。我很想知道是否有办法做到这一点。
然后,我使用以下分层数据模板来格式化树节点:
<HierarchicalDataTemplate DataType="{x:Type SomeViewModelType}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Source={StaticResource {x:Static SystemColors.HighlightBrushKey}}, Path=Color}" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{Binding Source={StaticResource {x:Static SystemColors.ControlBrushKey}}, Path=Color}" />
</StackPanel.Resources>
<Image SnapsToDevicePixels="True" Source="...">
</Image>
<TextBlock Text="{Binding Path=DisplayName}" Margin="5,0">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=IsSelected}" Value="True">
<Setter Property="Background" Value="{DynamicResource _CustomHighlightBrushKey}" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=IsSelected}" Value="True" />
<Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=IsSelectionActive}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="{DynamicResource _CustomControlBrushKey}" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Resources>
</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
请注意,我将系统画笔恢复为其原始(静态)值,以便可以正确呈现上下文菜单。