相关疑难解决方法(0)

将焦点设置在WPF中的文本框中

如何将焦点设置TextBox在WPF中的元素上

我有这个代码:

txtCompanyID.Focusable = true;
txtCompanyID.Focus();
Run Code Online (Sandbox Code Playgroud)

......但它不起作用.

任何的想法?

.net c# wpf textbox focus

97
推荐指数
7
解决办法
13万
查看次数

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

我正在敲打看起来像是一个简单的问题来修复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但没有获得键盘焦点.我错过了什么吗?除非另一个控件狠狠地保持键盘焦点,我很确定我没有编码,为什么这段相当简单的代码不能正常工作.

c# wpf xaml textbox focus

18
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×2

focus ×2

textbox ×2

wpf ×2

.net ×1

xaml ×1