Set focus on textbox in WPF

2019-01-07 14:01发布

问题:

How to set the focus on an TextBox element in WPF

I have this code:

txtCompanyID.Focusable = true;
txtCompanyID.Focus();

...but it is not working.

Any idea?

回答1:

In XAML:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=Box}">
   <TextBox Name="Box" />
</StackPanel>


回答2:

try FocusManager.SetFocusedElement

FocusManager.SetFocusedElement(parentElement, txtCompanyID)


回答3:

Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:

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

  private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
    txtCompanyID.Focus();
  }
}


回答4:

txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);

msdn:

There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.

You could break after the setting line and check the value of IsKeyboardFocused property. Also check if you really reach that line or maybe you set some other element to get focus after that.



回答5:

Try this : MyTextBox.Focus ( );



回答6:

None of this worked for me as I was using a grid rather than a StackPanel.

I finally found this example: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/

and modified it to this:

In the 'Resources' section:

    <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>

In my grid definition:

<Grid Style="{StaticResource FocusTextBox}" />