我的应用程序中有几个TreeView控件,它们都与此类似:
<TreeView SelectedItemChanged="TreeView_OnSelectedItemChanged" x:Name="AccountsTree" >
<TreeView.Resources>
<!-- styles -->
</TreeView.Resources>
<TreeViewItem Header="Things" >
<TreeViewItem.Resources>
<!--From: https://stackoverflow.com/a/17814749/107037-->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue" />
<!--<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />-->
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
<!--<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="Black" />-->
<HierarchicalDataTemplate DataType="{x:Type local:ThingEntity}" ItemsSource="{Binding Children, Mode=OneWay}">
<HierarchicalDataTemplate.Resources>
<!-- styles -->
</HierarchicalDataTemplate.Resources>
<StackPanel Orientation="Horizontal">
<i:Interaction.Behaviors>
<!-- drag 'n drop -->
</i:Interaction.Behaviors>
<Image x:Name="ThingIcon" />
<TextBlock Text="{Binding ThingName}" Margin="6,0,6,0" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeViewItem.Resources>
</TreeViewItem>
</TreeView>
我在这个答案中找到了更改SelectedItem颜色的简单方法:TreeView shows blue for selected item
有没有办法以某种方式封装SolidColorBrush定义的集合,以便在需要它们的所有TreeView中轻松重用它们?
或者,有没有办法将Brushes集合应用于所有TreeViewItem控件,就像
一样<Style TargetType="{x:Type TreeViewItem}">
<!-- style stuff -->
</Style>
将定义的Style应用于所有TreeViewItem控件?
谢谢 -
答案 0 :(得分:0)
样式可以有Resources
。简单。
<Style TargetType="{x:Type TreeViewItem}">
<Style.Resources>
<!--From: https://stackoverflow.com/a/17814749/107037-->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightBlue" />
<!--<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />-->
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
<!--<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="Black" />-->
<HierarchicalDataTemplate DataType="{x:Type local:ThingEntity}" ItemsSource="{Binding Children, Mode=OneWay}">
<HierarchicalDataTemplate.Resources>
<!-- styles -->
</HierarchicalDataTemplate.Resources>
<StackPanel Orientation="Horizontal">
<i:Interaction.Behaviors>
<!-- drag 'n drop -->
</i:Interaction.Behaviors>
<Image x:Name="ThingIcon" />
<TextBlock Text="{Binding ThingName}" Margin="6,0,6,0" />
</StackPanel>
</HierarchicalDataTemplate>
</Style.Resources>
</Style>
你也可以嵌套它们。 Style的资源可以包含另一个Style,它可以使用父样式的资源:
<Style x:Key="RedBlueTreeView" TargetType="TreeView">
<Style.Resources>
<SolidColorBrush x:Key="BlueBrush" Color="Red" />
<Style TargetType="TreeViewItem">
<Style.Resources>
<HierarchicalDataTemplate
DataType="{x:Type local:ThingEntity}"
ItemsSource="{Binding Children}"
>
<Label
Foreground="{StaticResource BlueBrush}"
Content="{Binding Stuff}"
/>
</HierarchicalDataTemplate>
</Style.Resources>
</Style>
</Style.Resources>
</Style>