WPF TabControl On SelectionChanged, set focus to a text field

纵然是瞬间 提交于 2019-11-30 17:09:03

问题


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.

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();
    }
}

If I just put txtusr.Focus() in a button event handler, it focuses exactly as I'd expect.

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.


回答1:


Try putting the .Focus() calls inside a dispatcher.BeginInvoke.

Dispatcher.BeginInvoke(new Action(() => { txtsvc.Focus(); }));


来源:https://stackoverflow.com/questions/3971179/wpf-tabcontrol-on-selectionchanged-set-focus-to-a-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!