WPF项目中如何移除鼠标悬停对象时显示的灰色边框
问题说明
基于MahApps.Metro框架开发的WPF程序运行时,鼠标光标悬停在界面对象上时,对象周围会出现灰色边框,效果参考:
现有核心XAML代码如下:
<mah:MetroWindow xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" FontFamily="Century Gothic" Title="Book Library" Height="660" Width="1250" > <Window.Resources> <DataTemplate x:Key="ItemTemplate"> <WrapPanel> <Image Width="200" Height="300" Stretch="Fill" Source="{Binding}"/> <TextBlock Text="{Binding}"/> </WrapPanel> </DataTemplate> </Window.Resources> <!-- 窗口其他业务内容 --> </mah:MetroWindow>
需求为移除该悬停触发的灰色外边框。
解决方案
该灰色边框由两类默认样式叠加生成:一是WPF原生的控件焦点视觉提示边框,二是MahApps.Metro为可交互控件、列表项容器预设的鼠标悬停状态边框,按以下方式修改即可移除:
- 对出现边框的控件或其项容器设置
FocusVisualStyle="{x:Null}",禁用原生焦点提示边框 - 重写对应控件的状态触发器,将鼠标悬停、选中状态下的边框刷设为透明,边框厚度设为0
如果你的列表项是通过ListBox/ListView承载、使用前文定义的ItemTemplate渲染,直接在Window.Resources节点(与现有ItemTemplate同级)中添加如下ListBoxItem样式,即可对所有列表项生效:
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}"> <Setter Property="FocusVisualStyle" Value="{x:Null}"/> <Setter Property="BorderThickness" Value="0"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="BorderBrush" Value="Transparent"/> <!-- 不需要悬停背景高亮则保留下行,需要则删除 --> <Setter Property="Background" Value="Transparent"/> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="BorderBrush" Value="Transparent"/> <Setter Property="Background" Value="Transparent"/> </Trigger> </Style.Triggers> </Style>
如果是Button、TextBox等独立控件出现该边框,直接给对应控件添加FocusVisualStyle="{x:Null}"属性,再重写控件模板中IsMouseOver状态下的BorderBrush为透明即可。
内容的提问来源于stack exchange,提问作者Микита Волошин
相关产品推荐
相关产品推荐

