WPF 自定义键盘焦点样式(FocusVisualStyle)
- 2020 年 2 月 10 日
- 筆記
WPF 自定义键盘焦点样式(FocusVisualStyle)
发布于 2017-12-17 15:34 更新于 2018-12-14 01:54
WPF 自带的键盘焦点样式是与传统控件样式搭配的,但 WPF 凭着其强大的自定义样式的能力,做出与传统控件样式完全不同风格的 UI 简直易如反掌。这时,其自带的键盘焦点样式(FocusVisualStyle
)就非常不搭了,改改会舒服得多。比如,改成 UWP 的样式。
本文将展示 WPF 自定义键盘焦点样式自定义的坑!

▲ WPF 自带的键盘焦点样式

▲ UWP 暗主题键盘焦点样式
其实微软官方文档 Styling for Focus in Controls, and FocusVisualStyle – Microsoft Docs 有说明 FocusVisualStyle
,但是——完全没有讲自定义好吗!
所以,我试着写一个样式以覆盖默认的样式:
<Style x:Key="{x:Static SystemParameters.FocusVisualStyleKey}"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Rectangle Margin="-3" StrokeThickness="3" Stroke="Gray" SnapsToDevicePixels="true"/> </ControlTemplate> </Setter.Value> </Setter> </Style>
运行一看,结果完全没有效果……

StackOverflow 上也有人说了这件事:xaml – How to redefine FocusVisualStyle for a WPF user control – Stack Overflow。Rohit Vats 说需要通过单独为 Button
设置才能生效并在回答中贴出了代码。
然而同样的代码应用到项目中,我们会发现,我们此前定义的无 Key 样式也失效了:

我的代码是这样的,试图用上此前定义的无 Key 样式,只是无效。
<Style x:Key="{x:Static SystemParameters.FocusVisualStyleKey}"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Rectangle Margin="-3" StrokeThickness="3" Stroke="Gray" SnapsToDevicePixels="true"/> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="FocusVisualStyle" Value="{StaticResource {x:Static SystemParameters.FocusVisualStyleKey}}"/> </Style>
那么,有没有办法能够一次定义整个应用程序生效呢?
答案是——

wpf – Change the FocusVisualStyle in the entire application – Stack Overflow 也承认了这一点。
FocusVisualStyle
样式的话,建议从零开始,定义每一个最底层样式的时候设置好 FocusVisualStyle
,其他样式定义的时候继承自最底层样式。- Styling for Focus in Controls, and FocusVisualStyle – Microsoft Docs
- xaml – How to redefine FocusVisualStyle for a WPF user control – Stack Overflow
- wpf – Change the FocusVisualStyle in the entire application – Stack Overflow
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 吕毅 (包含链接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (walter.lv@qq.com) 。