I have been putting off activity on SO because my current reputation is “1337”. 🙂
This is a question of “why” and not “how”. By default, it seems that WPF does not set focus to the first control in a window when it’s opening. In addition, when a textbox gets focus, by default it does not have it’s existing text selected. So basically when I open a window, I want focus on the first control of the window, and if that control is a textbox, I want it’s existing text (if any) to be selected.
I found some tips online to accomplish each of these behaviors, and combined them. The code below, which I placed in the constructor of my window, is what I came up with:
Loaded += (sender, e) =>
{
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
var textBox = FocusManager.GetFocusedElement(this) as TextBox;
if (textBox != null)
{
Action select = textBox.SelectAll;
//for some reason this doesn't work without using invoke.
Dispatcher.Invoke(DispatcherPriority.Loaded, select);
}
};
So, my question. Why does the above not work without using Dispatcher.Invoke? Is something built into the behavior of the window (or textbox) cause the selected text to be de-selected post-loading?
Maybe related, maybe not–another example of where I had to use Dispatcher.Invoke to control the behavior of a form:
All WPF controls have thread affinity. The
Dispatchermanages the thread that each control was created on (typically this is a single thread for every control in the application, but not necessarily). Work is queued on this thread and executed in priority order.Any UI-manipulating code has to be executed on the same thread as the control was created on – the
Dispatcherthread – and so any method has to invoke back to that thread before it can do anything that would affect the UI (such as selecting text in theTextBox).That said, it’s my understanding that the
Loadedeventhandler would fire on the Dispatcher thread by default, so I’m not entirely sure why you’re seeing this behaviour in your specific example!