我有一個WPF用戶控件,其中包含一個StackPanel,由於狀態更改而變得可見。當StackPanel變得可見時,我想將鍵盤焦點設置爲特定的子文本框。我發現,調用TextBox.Focus()將無法設置焦點(並返回false),除非我包裝在BeginInvoke的呼叫通話(大量的試驗和錯誤之後)如下所示:爲什麼我需要調用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);
}
兩個LogThreadMsg來電錶示,他們是在同一個(UI)線程如下所示:
[5232] Thread: 1 - CtlClientLookupPanel_IsVisibleChanged to Visible
[5232] Thread: 1 - CtlClientSearchText.Focus() returned True
那麼,爲什麼這個「黑客」需要?這似乎是某種時機問題,我正在尋找一個下游事件,可能會更好地調用Focus()而不訴諸於此,但尚未找到它。任何人都可以解釋這裏發生了什麼?
這個伎倆。謝謝! – 2010-09-16 01:34:35