Partilhar via


Como: Aplicar um FocusVisualStyle a um controle

This example shows you how to create a focus visual style in resources and apply the style to a control, using the FocusVisualStyle property.

Exemplo

The following example defines a style that creates additional control compositing that only applies when that control is keyboard focused in the user interface (UI). This is accomplished by defining a style with a ControlTemplate, then referencing that style as a resource when setting the FocusVisualStyle property.

An external rectangle resembling a border is placed outside of the rectangular area. Unless otherwise modified, the sizing of the style uses the ActualHeight and ActualWidth of the rectangular control where the focus visual style is applied. This example sets negative values for the Margin to make the border appear slightly outside the focused control.

<Page
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
>
  <Page.Resources>
    <Style x:Key="MyFocusVisual">
      <Setter Property="Control.Template">
        <Setter.Value>
          <ControlTemplate>
            <Rectangle Margin="-2" StrokeThickness="1" Stroke="Red" StrokeDashArray="1 2"/>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Page.Resources>
  <StackPanel Background="Ivory" Orientation="Horizontal">
    <Canvas Width="10"/>
    <Button Width="100" Height="30" FocusVisualStyle="{DynamicResource MyFocusVisual}">
      Focus Here</Button>
    <Canvas Width="100"/>
    <Button Width="100" Height="30" FocusVisualStyle="{DynamicResource MyFocusVisual}">
      Focus Here</Button>
  </StackPanel>
</Page>

A FocusVisualStyle is additive to any control template style that comes either from an explicit style or a theme style; the primary style for a control can still be created by using a ControlTemplate and setting that style to the Style property.

Focus visual styles should be used consistently across a theme or a UI, rather than using a different one for each focusable element. For details, see Estilo de foco em controles e FocusVisualStyle.

Consulte também

Referência

FocusVisualStyle

Conceitos

Styling and Templating

Estilo de foco em controles e FocusVisualStyle