This is an old revision of the document!


Focus Scopes

Sometimes, controls need to be grouped into focus scopes so that there is always a focused control in that group, irrespective of the actual keyboard focus (there can only be one keyboard focused control in an application at any given time).

To create a focus scope, make a parent control to be include FocusManager.IsFocusScope=“True”:

<StackPanel Name="pnlsideButtonsMain" FocusManager.IsFocusScope="True">
    <Button.../>
    <Button.../>
    <Button Name="btnReports".../>
</StackPanel>

Programmatically, in C#:

StackPanel pnlsideButtonsMain= new StackPanel();  
FocusManager.SetIsFocusScope(pnlsideButtonsMain, true);

To set the focus in a control:

// Sets the focused element in focus scope pnlsideButtonsMain
// pnlsideButtonsMain is a StackPanel.
FocusManager.SetFocusedElement(pnlsideButtonsMain, btnReports);

To style a control to show focus:

<Style x:Key="ButtonSimpleStyles" TargetType="{x:Type Button}">
    <Setter .../>
    <Setter .../>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border ...
                      x:Name="Border"  
                      CornerRadius="7" 
                      BorderThickness="1"
                      BorderBrush="SteelBlue">                
                      <ContentPresenter 
                        Margin="2"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        RecognizesAccessKey="True"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsKeyboardFocused" Value="true">
                        <Setter TargetName="Border" Property="BorderBrush" Value="SteelBlue" />
                        <Setter TargetName="Border" Property="Background" Value="{StaticResource MyGlassBlueBrushResource}" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                    <Trigger Property="IsFocused" Value="true">
                        <Setter TargetName="Border" Property="BorderBrush" Value="SteelBlue" />
                        <Setter TargetName="Border" Property="Background" Value="{StaticResource MyGlassBlueBrushResource}" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                    ...
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>