Keyboard.Focus不会在WPF文本框中工作(Keyboard.Focus does not

2019-08-04 08:00发布

我敲我的是什么样子这么简单的问题,头在WPF来解决,但我还没有发现,为什么我不能让我的应用程序按照我的计划行事。

我有一个弹出,在我的WPF应用程序时,用户按下Ctrl + F键一个小小的搜索框。 我想要的是搜索框的文本框里面闪烁插入符号,准备采取任何用户输入,而不需要点击它的用户。 下面是文本框是可见的,启用,XAML代码打可验证,tabstopable和可聚焦。

   <TextBox x:Name="SearchCriteriaTextBox" Text="{Binding SearchCriteria}" Focusable="True" IsEnabled="True" IsTabStop="True" IsHitTestVisible="True" Style="{DynamicResource SearchTextBoxStyle}" Grid.Column="1" Margin="5,10,0,5" />

在后面的代码,我有这个方法时,搜索框的可见性受到影响调用。 搜索框是在应用程序的启动加载。

    /// <summary>
    /// Handles events triggered from focusing on this view.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="dependencyPropertyChangedEventArgs">The key event args.</param>
    private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        if (!((bool) dependencyPropertyChangedEventArgs.NewValue))
        {
            return;
        }

        SearchCriteriaTextBox.Focus();
        Keyboard.Focus(SearchCriteriaTextBox);
        SearchCriteriaTextBox.Select(0, 0);

        if (SearchCriteriaTextBox.Text.Length > 0)
        {
            SearchCriteriaTextBox.SelectAll();
        }
    }

问题是,代码被调用,组件成为IsFocused = true,但不会获得键盘焦点。 我缺少的东西吗? 除非另一个控制保持凶猛抱到键盘焦点,我敢肯定我没有代码,为什么会这样一段相当简单的代码将无法正常工作。

Answer 1:

作为一种变通方法,您可以尝试使用Dispatcher将焦点设置在以后的DispatcherPriority ,如Input

Dispatcher.BeginInvoke(DispatcherPriority.Input,
    new Action(delegate() { 
        SearchCriteriaTextBox.Focus();         // Set Logical Focus
        Keyboard.Focus(SearchCriteriaTextBox); // Set Keyboard Focus
     }));

从你的问题的描述,这听起来像你没有键盘焦点设置。 WPF可以有多个聚焦范围,所以多个元件可以具有逻辑焦点( IsFocused = true ),然而仅一个元件可以具有键盘焦点和将接收键盘输入。

你的代码贴应该正确设置焦点,所以必须有所之后发生的移动键盘焦点从你的TextBox 。 在稍后通过调度优先级设置的重点,你会确保设置键盘焦点到您的SearchCriteriaTextBox一事无成最后。



Answer 2:

如果它可以帮助任何人,我有这个问题,我的应用程序曾与放置在单独的网格与可见性数据绑定多个用户控制主窗口。 由于格在那里,当应用程序被内置在.Focus()呼吁加载或构造将在构建时被调用,而不是在可见的时间。

无论如何,我由栅格上的MouseEnter事件调用.Focus()固定它。 对我来说工作正常。



文章来源: Keyboard.Focus does not work on text box in WPF