Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can get your <code>.Focus()</code> call to stick by using <code>Dispatcher.BeginInvoke</code> to delay the actual <code>Focus()</code> call until the <code>Click</code> or <code>MouseDown</code> event handler has completed and the calling code has finished working.</p> <p>Here is how to do it:</p> <pre><code>private void ListBoxItem_MouseDown(object sender, MouseButtonEventArgs e) { //Keyboard.Focus(FocusedTextBox); // May be necessary to uncomment this in some scenarios Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =&gt; { Keyboard.Focus(FocusedTextBox); }); } </code></pre> <p>Here is the sequence of events:</p> <ol> <li>WPF calls your MouseDown handler</li> <li>Your MouseDown handler asks the WPF Dispatcher to call it back when all DispatcherPriority.Input (and higher) invocations have been completed</li> <li>Your MouseDown handler returns and the calling code completes its processing</li> <li>Any other input events in the queue are processed</li> <li>Your Action is called, and your code calls <code>Keyboard.Focus(FocusedTextBox)</code> to set the focus.</li> </ol> <p>The key point here is that <strong><code>KeyboardFocus.Focus()</code> is not called until after your handler has returned and WPF has completed all pending input processing</strong>.</p> <p>It is possible that the <code>KeyboardFocus.Focus()</code> call itself may trigger ListBox to steal focus from you. I haven't checked this. If that is the case, the solution would be to call it twice: Once from the MouseDown handler and again from the Action scheduled by the MouseDown handler. So if it doesn't work with the first line commented out, uncomment it and try again.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload