#311 – Giving Focus to a Control, Part II
June 1, 2011 Leave a comment
You can give focus to a specific control at run-time using the Keyboard.Focus static method. You can also give focus to any control that inherits from UIElement using the control’s Focus method.
public MainWindow() { this.InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { // On startup, set focus to first TextBox in window txtFirst.Focus(); }
The difference between these two methods is:
- Keyboard.Focus just sets keyboard focus
- UIElement.Focus tries to set keyboard focus. If the control fails to get keyboard focus, the method sets logical focus to the control