J'ai un UserControl WPF qui contient un StackPanel rendu visible suite à un changement d'état. Lorsque le StackPanel devient visible, je veux définir le focus du clavier sur un TextBox enfant particulier. J'ai trouvé (après beaucoup d'essais et d'erreurs) que l'appel à TextBox.Focus() ne parviendra pas à mettre au point (et retourne false) à moins que je conclurai cet appel dans un appel BeginInvoke comme indiqué ici:Pourquoi dois-je appeler Dispatcher.BeginInvoke à SetFocus?
private void CtlClientLookupPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) {
LogThreadMsg(string.Format("CtlClientLookupPanel_IsVisibleChanged to {0}", CtlClientLookupPanel.Visibility));
if (CtlClientLookupPanel.Visibility == Visibility.Visible) {
Dispatcher.BeginInvoke((ThreadStart)delegate {
bool gotFocus = CtlClientSearchText.Focus();
LogThreadMsg(string.Format("CtlClientSearchText.Focus() returned {0}", gotFocus));
});
}
}
private void LogThreadMsg(string msg) {
string fullMsg = string.Format("Thread: {0} - {1}", Thread.CurrentThread.ManagedThreadId, msg);
System.Diagnostics.Trace.WriteLine(msg);
}
les deux appels LogThreadMsg indiquent qu'ils sont sur le même fil (IU) comme indiqué ici:
[5232] Thread: 1 - CtlClientLookupPanel_IsVisibleChanged to Visible
[5232] Thread: 1 - CtlClientSearchText.Focus() returned True
Alors pourquoi est-ce « hack » nécessaire? Cela semble être une sorte de problème de synchronisation et je cherchais un événement en aval qui serait peut-être un meilleur endroit pour appeler Focus() sans avoir recours à cela, mais je ne l'ai pas trouvé. Quelqu'un peut-il expliquer ce qui se passe ici?
Cela a fait l'affaire. Merci! –