控件获取焦点除了用鼠标外,可以通过键盘来获取,比如Tab键或者方向键等,需要设置控件获取键盘焦点时的样式,可以通过设置FrameworkElemnt.FocusVisualStyle属性,
因为几乎所有常用的控件都继承了FrameworkElement,所以绝大部分控件都拥有该属性
// Summary:
// Gets or sets a property that enables customization of appearance, effects,
// or other style characteristics that will apply to this element when it captures
// keyboard focus. This is a dependency property.
//
// Returns:
// The desired style to apply on focus. The default value as declared in the
// dependency property is an empty static System.Windows.Style. However, the
// effective value at run time is often (but not always) a style as supplied
// by theme support for controls.
public Style FocusVisualStyle { get; set; }
huangcongde
通过以上代码可以看到,FocusVisualStyle就是Style类型的属性,所以可以这样:
<Window x:Class="FocusVisualStyleDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="">
<Window.Resources>
<!--将获取焦点的样式设置为红色边框-->
<Style x:Key="newFocusStyle">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="-2" StrokeThickness="" Stroke="Red"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Margin="122.275,36.227,139.525,217.173" />
<Button Margin="122.275,127.2,139.525,126.2" FocusVisualStyle="{DynamicResource newFocusStyle}"/>
<Button Margin="97.919,209.328,106.481,32.872" FocusVisualStyle="{x:Null}"/>
</Grid>
</Window>
huangcongde
而有些控件在获取焦点后,出现黑色虚线的效果,就是因为该属性的原因,如果想去掉这种效果,只需要将FocusVisualStyle设置为{x:Null}即可
默认的获取键盘焦点样式,会出现黑色虚线边框
自定义样式后的效果
将FocusVisualStyle设置为{x:null}的效果