Keyboard.Focus在WPF中的文本框上不起作用

leg*_*ing 18 c# wpf xaml textbox focus

我正在敲打看起来像是一个简单的问题来修复wpf,但我还没有发现为什么我不能让我的应用程序按照我的计划行事.

当用户按下ctrl + f时,我的wpf应用程序中会弹出一个小搜索框.我想要的只是插入符号在搜索框文本框内闪烁,准备好接受任何用户输入而无需用户点击它.以下是文本框的xaml代码,该代码可见,启用,命中可测试,tabstopable和focusable.

   <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" />
Run Code Online (Sandbox Code Playgroud)

在后面的代码中,我在搜索框的可见性受到影响时调用此方法.搜索框在应用程序的开头加载.

    /// <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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,代码被调用,组件变为IsFocused = true但没有获得键盘焦点.我错过了什么吗?除非另一个控件狠狠地保持键盘焦点,我很确定我没有编码,为什么这段相当简单的代码不能正常工作.

Rac*_*hel 61

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

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

从您的问题的描述,听起来你没有键盘焦点设置.WPF可以有多个焦点范围,因此多个元素可以具有逻辑焦点(IsFocused = true),但是只有一个元素可以具有键盘焦点并且将接收键盘输入.

您发布的代码应正确设置焦点,因此必须先发生一些事情才能将键盘焦点移出您的TextBox.通过将焦点设置为稍后的调度程序优先级,您将确保将键盘焦点设置为SearchCriteriaTextBox最后完成.

  • 刚刚发现,即将发布我自己的回复,感谢Rachel它在多线程环境中完美运行.编辑:您可以调用Dispatcher.BeginInvoke(DispatcherPriority.Input,new ThreadStart(()=> SearchCriteriaTextBox.Focus())); 得到相同的结果,而不必调用文本框焦点 (2认同)
  • 有人对这个问题有解释吗? (2认同)
  • 我尝试了从键盘焦点到将 Focusable 设置为 true 并将可见性设置为 true 然后调用 Focus 的所有方法,还尝试了 FocusManager 但这是唯一有效的方法。 (2认同)