Search code examples
c#wpffocusscrollbaruielement

Programmatically Focus on a ScrollBar


In the code shown,

  • Why doesn't the focus shift to the ScrollBar element?
  • Why does UIElement.Focus (TheScrollBar.Focus) return False?

enter image description here

XAML:

    <Window x:Class="ScrollBarFocus.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:ScrollBarFocus"
        mc:Ignorable="d"
        ResizeMode="CanMinimize"
        SizeToContent="WidthAndHeight"
        Title="MainWindow">
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Click="Button_Click" Content="Click me to focus on the ScrollBar"/>
        <ScrollBar x:Name="TheScrollBar" Grid.Row="1" Maximum="99" Orientation="Horizontal" SmallChange="1"/>
        <TextBox BorderBrush="Black" Grid.Row="2" IsReadOnly="True" Text="{Binding ElementName=TheScrollBar, Path=Value, StringFormat={}{0:####0}}" TextAlignment="Center"/>
        <Label x:Name="TheStatus" Grid.Row="3" Height="40" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="400"/>
        <x:Code>
            <![CDATA[
                void Button_Click(object sender, RoutedEventArgs e) {
                    TheStatus.Content = "TheScrollBar.Focus() == " + TheScrollBar.Focus().ToString();
                }
            ]]>
        </x:Code>
    </Grid>
</Window>

C#:

    using System.Windows;
    namespace ScrollBarFocus {
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
            }
        }
   }

I'm obviously missing something here. Does UIElement.Focus not accept focus?


Solution

  • To the Button_Click method, add the statement TheScrollBar.Focusable = true;:

        void Button_Click(object sender, RoutedEventArgs e)
        {
            TheScrollBar.Focusable = true;
            TheStatus.Content = "TheScrollBar.Focus() == " + TheScrollBar.Focus().ToString();
        }
    

    enter image description here ...works fine ("Won't bust; won't rust; won't collect dust ... won't even wake the baby!").