Saturday, November 5, 2016

Focusing was unexpectedly hard!

Today i demonstrate how to set the focus on a textbox after selecting a tab item. I assumed that doing so would just require a call to textboxname.Focus. Of course if I had been right, i would have had to blog about the topic of my next blog post today....


I was working on a WPF application in visual basic containing a tab control with two TabItems. My goal was to set the keyboard focus on a specific textbox contained on the second tab item, as soon as it was clicked. After trying to call the Focus method from tabcontrol.SelectionChanged i did a little digging, and apparently the page was still too busy updating its layout when i called the focus method.

Explicitly calling UpdateLayout did not work. The way around that was to set the focus asynchronously, by using the windows dispatcher. Doing this creates a new thread , allowing the old threat to continue doing its job, while the new thread sets the focus.

The code i have used for this:

Application.Current.Dispatcher.BeginInvoke _
(System.Windows.Threading.DispatcherPriority.Background, _
New Action(Sub() txtWatermark.Focus()))

This code produced the desired result, by creating a new sub with one instruction, called a Lambda Expression. If you would like to have a bigger sub to do the work, the code becomes:


dim action as Action = sub() FocusOnTextBlock()

Private Sub NextTabItem
TabsApp.SelectedIndex += 1
Application.Current.Dispatcher.BeginInvoke
(System.Windows.Threading.DispatcherPriority.Background, action ))
End Sub

Private Sub FocusOnTextblock()
txtWatermark.Focus()
End Sub
On a side note: I just tested the methods shown in the linked article on Focus. It did not work for me. If I missed another way to set the focus, let me know! I hope that this helps someone out and happy coding!

No comments:

Post a Comment