我正在尝试在树视图的所选项目周围设置圆形边框(就像Vista上的Windows资源管理器中的那个)。问题是以下代码中的触发器似乎不起作用。看起来IsSelected属性始终为false。
<TreeView x:Name="m_treeView" BorderThickness="0" d:LayoutOverrides="Width, Height">
<TreeView.Resources>
<Style TargetType="TreeViewItem">
<Style.Resources>
<Brush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</Brush>
</Style.Resources>
</Style>
</TreeView.Resources>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:DirectoryPresentationBase}" ItemsSource="{Binding Children}">
<TreeViewItem>
<TreeViewItem.Header>
<Border Name="SelectedBorder" CornerRadius="3" Background="#EFF8FD" BorderBrush="#99DEFD"
BorderThickness="1" >
<StackPanel Orientation="Horizontal">
<interactivity:Interaction.Behaviors>
<local:TreeViewExpandBehavior AssociatedTreeView="{Binding ElementName=m_treeView}"/>
</interactivity:Interaction.Behaviors>
<Image x:Name="img" Width="24" Height="16" Stretch="None" Source="{Binding SmallIcon}"/>
<TextBlock Text="{Binding Name}" Margin="5,0" />
</StackPanel>
</Border>
</TreeViewItem.Header>
</TreeViewItem>
<HierarchicalDataTemplate.Triggers>
<Trigger Property="TreeViewItem.IsSelected" Value="True">
<Setter Property="Background" TargetName="SelectedBorder" Value="Red"/>
<Setter Property="BorderBrush" TargetName="SelectedBorder" Value="Green"/>
</Trigger>
<Trigger Property="TreeViewItem.IsSelected" Value="False">
<Setter Property="Background" TargetName="SelectedBorder" Value="Transparent"/>
<Setter Property="BorderBrush" TargetName="SelectedBorder" Value="Transparent"/>
</Trigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
答案 0 :(得分:4)
首先,删除触发器IsSelected=False
。当IsSelected
变为True
时,它会自动还原所有更改。
其次,将触发器移至TreeView.Resources
:
<TreeView.Resources>
<Style TargetType="TreeViewItem">
.....
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="BorderBrush" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
</TreeView.Resources>
第三,删除TreeViewItem
标记。直接在Border
内使用HierarchicalDataTemplate
。那是因为你放在HierarchicalDataTemplate
中的所有东西都已在某些TreeViewItem
内实例化了。
第四,将border的背景和边框画笔绑定到treeviewitem的那些
Background="{Binding Background, RelativeSource={RelativeSource AncestorType=TreeViewItem}}"
BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType=TreeViewItem}}"