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

pri*_*kar 97 .net c# wpf textbox focus

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

我有这个代码:

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

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

任何的想法?

use*_*Bee 137

在XAML中:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这种方法,因为它与MVVM保持一致. (8认同)
  • 焦点元素是只读的,如何在xaml中设置?我使用了这个,但它不起作用 &lt;Style.Triggers&gt; &lt;Trigger Property="Validation.HasError" Value="True"&gt; &lt;Setter Property="FocusManager.FocusedElement" Value="{Binding Source={RelativeSource Self}}" /&gt; &lt;/触发器&gt; &lt;/Style.Triggers&gt; (2认同)

Ars*_*yan 49

尝试FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)
Run Code Online (Sandbox Code Playgroud)

  • FocusManager.SetFocusedElement(FocusManager.GetFocusScope(parentElement),parentElement); (10认同)
  • 如果要设置的元素集中于*是*父元素oO,该怎么办? (5认同)

Pet*_*ber 49

到目前为止,没有人解释为什么问题中的代码不起作用.我的猜测是代码放在Window的构造函数中.但此时设定焦点还为时过早.一旦Window准备好进行交互,就必须完成它.代码的最佳位置是Loaded事件:

public KonsoleWindow() {
  public TestWindow() {
    InitializeComponent();
    Loaded += TestWindow_Loaded;
  }

  private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
    txtCompanyID.Focus();
  }
}
Run Code Online (Sandbox Code Playgroud)


Sve*_*lov 23

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

MSDN:

整个桌面上只有一个元素具有键盘焦点.在WPF中,具有键盘焦点的元素将IsKeyboardFocused设置为true.

您可以在设置行后中断并检查IsKeyboardFocused属性的值.还要检查你是否真的到达那一行,或者你可以设置一些其他元素来获得焦点.


小智 16

试试这个 : MyTextBox.Focus ( );

  • 这是最优雅的答案,它也不需要您指定父项。谢谢你,这对我来说很棒! (2认同)

Any*_*ope 13

这对我来说都不起作用,因为我使用的是网格而不是StackPanel.

我终于找到了这个例子:http: //spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/

并将其修改为:

在"资源"部分:

    <Style x:Key="FocusTextBox" TargetType="Grid">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
Run Code Online (Sandbox Code Playgroud)

在我的网格定义中:

<Grid Style="{StaticResource FocusTextBox}" />
Run Code Online (Sandbox Code Playgroud)

  • 这也对我有用。其余的不是。感谢您的链接,这很有趣。同样有趣的是,这种简单的事情可能是如此复杂。 (2认同)
  • 无论容器是Gird还是StackPanel,上面的答案都可以正常工作.由于你的网格结构不清楚,很难说出什么可能出错.很高兴看到替代品. (2认同)

ane*_*los 8

如果您还没有在其他答案中找到解决方案,那么我就是这样解决问题的。

Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
    TEXTBOX_OBJECT.Focus();
}), System.Windows.Threading.DispatcherPriority.Render);
Run Code Online (Sandbox Code Playgroud)

据我了解,其他解决方案可能不起作用,因为Focus()在应用程序呈现其他组件之前调用了 。

  • 这个答案应该得到更好的排名。 (3认同)