WPF TabControl On SelectionChanged,将焦点设置到文本字段

发布于 2024-09-28 08:02:58 字数 667 浏览 0 评论 0原文

我有一个选项卡控件和一些选项卡项。我成功监听 SelectionChanged 事件,并检查我感兴趣的选项卡是否是当前选定的选项卡。

我正在使用这段代码(如下),并单步执行调试器,我可以看到我的分支逻辑按设计工作;但是,我遇到的问题是,某些内容正在覆盖对 txt.Focus() 的调用,因为显示正确的选项卡项后,焦点不在文本框上。

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() 放入按钮事件处理程序中,它就会完全按照我的预期进行聚焦。

我怀疑这与调用 .Focus() 方法时未加载 tabitem 内容有关,但我不确定如何修复它。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别把无礼当个性 2024-10-05 08:02:58

尝试将 .Focus() 调用放入 Dispatcher.BeginInvoke 中。

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

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

Dispatcher.BeginInvoke(new Action(() => { txtsvc.Focus(); }));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文