我有一个UserControl
包含一个TextBox
. 当用户控件变得可见时,我给予TextBox
焦点。有人可以澄清为什么我必须使用Dispatcher
?
public MyUserControl()
{
InitializeComponent();
this.IsVisibleChanged += VisibilityChanged;
}
案例1(作品):
private void VisibilityChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.Visibility == Visibility.Visible)
{
this.Dispatcher.BeginInvoke((Action)delegate
{
Keyboard.Focus(this.InputTextBox);
}, DispatcherPriority.Render);
}
}
案例2(不起作用):
private void VisibilityChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.Visibility == Visibility.Visible)
{
Keyboard.Focus(InputTextBox);
}
}