I have a UserControl that contains a TextBox. When the user control becomes visible, I give the TextBox focus. Could somebody clarify why I have to do this using the Dispatcher?
public MyUserControl()
{
InitializeComponent();
this.IsVisibleChanged += VisibilityChanged;
}
Case 1 (works):
private void VisibilityChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.Visibility == Visibility.Visible)
{
this.Dispatcher.BeginInvoke((Action)delegate
{
Keyboard.Focus(this.InputTextBox);
}, DispatcherPriority.Render);
}
}
Case 2 (does not work):
private void VisibilityChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.Visibility == Visibility.Visible)
{
Keyboard.Focus(InputTextBox);
}
}
could you call
Keyboard.Focus(InputTextBox);in the event handler forInputTextBox.IsVisibleChangedinstead ofthis.IsVisibleChanged?If this works then I suspect the
this.IsVisibleChangedevent is raised before the layout panel has updated the children controls, i.e perhapsInputTextBoxis still not visible when you put focus on it withoutBeginInvoke.