Focus on a Disabled Control
This is a trick question. Obviously you can't focus on a disabled control.
But in code, if you call...
myControl.isEnabled = true;
You'd expect it to work. Turns out it doesn't. To see what I mean, please load the code below into your own project. Change the namespace to your own, obviously.
When you first run the example, the first textbox gets focus initially. Type in anything you want. Hit tab to go to the second textbox.
The second textbox has an event handler hooked up to its LostFocus event. The handler looks at what you typed into the second textbox. If you typed in an integer, it's supposed to enable the third textbox (it starts out disabled), and move focus to it. What in fact winds up happenning is it enables the third textbox correctly, but focus then goes back to the first textbox.
This only happens when the third textbox is disabled. In other words, if you enter an integer into TextBox2 when TextBox3 is already enabled (from a previous integer in TextBox2), TextBox3 gets focus as you would expect.
Here's the code. Thanks for your help.
Title="FocusTest" Height="300" Width="300">
<TextBox x:Name="TextBox1" Margin="5" Width="100" GotFocus="textBox_GotFocus"></TextBox>
<TextBox x:Name="TextBox2" Margin="5" Width="100" GotFocus="textBox_GotFocus" LostFocus="TextBox2_LostFocus"></TextBox>
<TextBox x:Name="TextBox3" Margin="5" Width="100" GotFocus="textBox_GotFocus" IsEnabled="False"></TextBox>
public partial class FocusTest : Window
this.Loaded += new RoutedEventHandler(FocusTest_Loaded);
void FocusTest_Loaded(object sender, RoutedEventArgs e)
private void TextBox2_LostFocus(object sender, RoutedEventArgs e)
string theText = TextBox2.Text;
if (int.TryParse(theText, out i))
TextBox3.IsEnabled = true;
TextBox3.IsEnabled = false;
private void textBox_GotFocus(object sender, RoutedEventArgs e)
(sender as TextBox).SelectAll();