我已经找到了(有点哈克),但重量轻的解决这个问题。我发现这个问题很老,但是,我会在这里发布解决方案供其他人查找。
在我的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>
注意,我恢复系统刷到原来的(静态)值,所以上下文菜单可以正确地呈现。
这很有道理,但它不像您提供的示例那么容易。每次尝试使用TargetName来解决TextBlock问题时,都会收到一条错误消息,指出它无法访问。 – AKoran 2009-11-10 14:40:54
http://stackoverflow.com/questions/248545/wpf-trigger-for-isselected-in-a-datatemplate-for-listbox-items – Guy 2009-11-10 15:52:12
不要采取这种错误的方式,但它并没有帮助新手对WPF来说,当你指出一个只是有点接近我想要做的事情的例子。无论我尝试什么,每当我回到TextBlock时,我都会得到一个“TargetName属性无法在Style Setter上设置”的错误。 – AKoran 2009-11-10 18:44:26