WPF TabControl在SelectionChanged上,将焦点设置为文本字段 [英] WPF TabControl On SelectionChanged, set focus to a text field
问题描述
SelectionChanged
事件,并检查我感兴趣的标签是否是当前选定的标签。 我正在使用这个代码(下面),并通过调试器,我可以看到,我的分支逻辑工程设计;然而,我遇到的问题是,重写这个调用到 txt.Focus()
,因为在正确的标签项被显示之后,焦点不在文本上
private void tabMain_SelectionChanged(object sender,SelectionChangedEventArgs e)
在按钮事件处理程序中,它完全按照我的预期进行对焦。
{
//完全相同的行为有和没有这条线
e.Handled = true; (e.AddedItems.Contains(usrTab))
{
txtusr.Focus();
if
else if(e.AddedItems.Contains(svcTab))
{
txtsvc.Focus();
$ p $如果我只是把code txtusr .Focus()
我怀疑这与在
.Focus()
时未加载的tabitem内容有关。方法被调用,但我不知道如何去解决它。尝试把.Focus()调用在调度程序.BeginInvoke中。Dispatcher.BeginInvoke(new Action((=)=> {txtsvc.Focus();} ));
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.解决方案Try putting the .Focus() calls inside a dispatcher.BeginInvoke.
Dispatcher.BeginInvoke(new Action(() => { txtsvc.Focus(); }));
这篇关于WPF TabControl在SelectionChanged上,将焦点设置为文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!