如何将焦点设置TextBox
在WPF中的元素上
我有这个代码:
txtCompanyID.Focusable = true;
txtCompanyID.Focus();
Run Code Online (Sandbox Code Playgroud)
......但它不起作用.
任何的想法?
我正在敲打看起来像是一个简单的问题来修复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但没有获得键盘焦点.我错过了什么吗?除非另一个控件狠狠地保持键盘焦点,我很确定我没有编码,为什么这段相当简单的代码不能正常工作.