转载自csdn:WPF新手之如何自定义TreeView点击后的背景色
其它控件也同样适用:
对于一时找不出好办法的情况,直接用StyleSnooper找到所需的控件,查看它的默认Style。然后找到所需的设置,如这里是找到
[xhtml] view plaincopy
1 <Trigger Property="TreeViewItem.IsSelected"> 2 <Setter Property="Panel.Background" TargetName="Bd"> 3 <Setter.Value> 4 <DynamicResource ResourceKey="{x:Static SystemColors.HighlightBrushKey}" 5 /> 6 </Setter.Value> 7 </Setter> 8 <Setter Property="TextElement.Foreground"> 9 <Setter.Value> 10 <DynamicResource ResourceKey="{x:Static 11 SystemColors.HighlightTextBrushKey}" /> 12 </Setter.Value> 13 </Setter> 14 <Trigger.Value> 15 <s:Boolean> 16 True</s:Boolean> 17 </Trigger.Value> 18 </Trigger> 19 <MultiTrigger> 20 <MultiTrigger.Conditions> 21 <Condition Property="TreeViewItem.IsSelected"> 22 <Condition.Value> 23 <s:Boolean> 24 True</s:Boolean> 25 </Condition.Value> 26 </Condition> 27 <Condition Property="Selector.IsSelectionActive"> 28 <Condition.Value> 29 <s:Boolean> 30 False</s:Boolean> 31 </Condition.Value> 32 </Condition> 33 </MultiTrigger.Conditions> 34 <Setter Property="Panel.Background" TargetName="Bd"> 35 <Setter.Value> 36 <DynamicResource ResourceKey="{x:Static 37 SystemColors.ControlBrushKey}" /> 38 </Setter.Value> 39 </Setter> 40 <Setter Property="TextElement.Foreground"> 41 <Setter.Value> 42 <DynamicResource ResourceKey="{x:Static 43 SystemColors.ControlTextBrushKey}" /> 44 </Setter.Value> 45 </Setter> 46 </MultiTrigger>
这是当项被选中之时的触发器。现在只要把对应的值{x:Static SystemColors.HighlightBrushKey}在Style.Resources中重新定义即可:
[xhtml] view plaincopy
1 <Style.Resources> 2 <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="PapayaWhip"/> 3 <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="PapayaWhip"/> 4 <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/> 5 </Style.Resources>
两个注意点:
①原来Style中可能会有自定义的Resources,也许是出于完备性的考虑,其实并没有内容
[xhtml] view plaincopy
1 <Style.Resources> 2 <ResourceDictionary /> 3 </Style.Resources>
这个需要把它删除,因为只能出现一处。
②可能需要在Windows中加入命名空间
xmlns:s="clr-namespace:System;assembly=mscorlib"
但是尚有两个问题未决:
①由于默认Style中很多地方相互引用,因此往往需要把整个Style全部拷贝过来(也许我水平高了以后可以不这样)
②由于①的原因,TreeViewItem前面的小三角失去了效果。
PS:学后记:其实根本不用这么麻烦,只要找到默认Style中的值,在Resources中将相应的值进行重新定义即可:
[xhtml] view plaincopy
1 <Grid.Resources> 2 <Style TargetType="TreeViewItem"> 3 <Style.Resources> 4 <!--SelectedItem with focus--> 5 <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue" Opacity=".2"/> 6 <!--SelectedItem without focus--> 7 <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="LightBlue" Opacity=".2"/> 8 </Style.Resources> 9 </Style> 10 </Grid.Resources>
)
时间: 2024-10-21 04:37:37