【问题标题】:Programmatically Focus on a ScrollBar以编程方式关注 ScrollBar
【发布时间】:2016-10-12 21:40:05
【问题描述】:

在显示的代码中,

  • 为什么焦点不转移到 ScrollBar 元素?
  • 为什么UIElement.Focus (TheScrollBar.Focus) 返回 False?

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();
            }
        }
   }

我显然在这里遗漏了一些东西。 UIElement.Focus不接受焦点吗?

【问题讨论】:

    标签: c# wpf focus scrollbar uielement


    【解决方案1】:

    简单的答案:滚动条不接受焦点:)。

    【讨论】:

    • 所以......假设你想让用户移动,只使用键盘,滚动条的拇指,你会做什么?
    • (例如,假设你在飞机上,飞机很乱,你必须在到达之前完成一些事情,而触控板不会破解它。)......不幸经历......多次......
    • 我猜你必须编写代码来处理击键,然后将值应用于滚动条......叹息。我想知道让滚动条忽略焦点的决定背后的原因是什么。
    • @user1601638,您确定要滚动条吗?也许你真的想要一个滑块控件?
    【解决方案2】:

    在 Button_Click 方法中,添加语句 TheScrollBar.Focusable = true;:

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

    ...工作正常(“不会爆裂;不会生锈;不会收集灰尘...甚至不会吵醒婴儿!”)。

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 1970-01-01
      • 2015-07-31
      • 2010-09-05
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多