問題描述
我有一個選項卡控件和一些選項卡項.我正在成功監(jiān)聽 SelectionChanged
事件,并檢查我感興趣的選項卡是否是當(dāng)前選定的選項卡.
I have a tab control, and a few tab items. I am successfully listening to the SelectionChanged
event, and checking if the tab I'm interested in is the currently selected one.
我正在使用這段代碼(如下),并逐步通過調(diào)試器,我可以看到我的分支邏輯按設(shè)計工作;但是,我遇到的問題是某些東西覆蓋了對 txt.Focus()
的調(diào)用,因為在顯示正確的選項卡項后,焦點不在文本框上.
I'm using this code (below), and stepping through the debugger, I can see that my branching logic works as designed; however, the issue I'm having is that something is overriding this call to txt.Focus()
because after the correct tab item is displayed, the focus is not on the text box.
private void tabMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// exact same behavior with and without this line
e.Handled = true;
if (e.AddedItems.Contains(usrTab))
{
txtusr.Focus();
}
else if (e.AddedItems.Contains(svcTab))
{
txtsvc.Focus();
}
}
如果我只是將 txtusr.Focus()
放在按鈕事件處理程序中,它會完全按照我的預(yù)期聚焦.
If I just put txtusr.Focus()
in a button event handler, it focuses exactly as I'd expect.
我懷疑這與調(diào)用 .Focus()
方法時未加載 tabitem 內(nèi)容有關(guān),但我不確定如何修復(fù)它.
I suspect that this has to do with the tabitem content not being loaded at the time the .Focus()
method is called, but I'm not sure how to go about fixing it.
推薦答案
嘗試將 .Focus() 調(diào)用放在 dispatcher.BeginInvoke 中.
Try putting the .Focus() calls inside a dispatcher.BeginInvoke.
Dispatcher.BeginInvoke(new Action(() => { txtsvc.Focus(); }));
這篇關(guān)于WPF TabControl On SelectionChanged,將焦點設(shè)置到文本字段的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!