确保按钮在 ScrollViewer 中获得焦点

Ensuring button takes focus within ScrollViewer

糟糕! 完全忘记了我拥有的应用程序范围样式,这是按钮上的边距。我修改了代码和 gif 以反映这一点。

我有以下 XAML 标记:

<Window x:Name="SampleMainWindow1" x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="300">
<DockPanel>

    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" Grid.Row="1">
            <StackPanel Orientation="Horizontal">
                <Button Margin="40,40,40,40" Width="Auto">Button 1</Button>
                <Button Margin="40,40,40,40" Width="Auto">Button 2</Button>
                <Button Margin="40,40,40,40" Width="Auto">Button 3</Button>
                <Button Margin="40,40,40,40" Width="Auto">Button 4</Button>
            </StackPanel>
        </ScrollViewer>

    </Grid>

</DockPanel>

但是,当一个按钮获得焦点时,例如 Button 1,当我按下右键时,我立即将焦点放在 Button 2 上,但是如您所见,我必须向右按几下在 Button 3 获得焦点之前更多次,对于 Button 4.

也是如此

如何才能让按键立即聚焦到下一个按钮,并且该按钮会滚动到视图中?

通过将 ScrollViewer.CanContentScroll 设置为 true 让面板滚动。