我如何找出焦点在我的WPF应用程序? [英] How do I find out where the focus is going in my WPF application?

查看:289
本文介绍了我如何找出焦点在我的WPF应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的WPF应用程序中有一个搜索屏幕。该屏幕实现为TabControl的TabItem中的UserControl。当用户切换到搜索选项卡时,我希望焦点进入一个特定的字段。

所以我添加了一个Loaded事件处理程序到Xaml中的UserControl标签,我调用了控件的Focus方法,我想在Loaded事件处理程序中初始化焦点。这很好,直到我升级了我今天使用的Telerik控制库。现在,当我切换到搜索选项卡,焦点不在我想要的领域,但我不能告诉什么控制有焦点。



我想聚焦的领域已经有GotFocus& LostFocus事件处理程序由于其他原因。我记得在Win Forms中,LostFocus事件处理程序参数告诉你哪个控件将获得焦点。所以我在我的LostFocus处理程序中放置了一个断点。发现WPF中的LostFocus事件处理函数的参数不包含这些信息。

如何在不将每个控件的GotFocus处理程序放在焦点的情况下,在我的UserControl中?



Tony

解决方案

断点在 LostKeyboardFocus 附加事件而不是 LostFocus 事件。它使用 KeyboardFocusChangedEventArgs 具有显示哪个元素具有焦点并且焦点在哪里的属性的类。

  private void textBox1_LostKeyboardFocus(Object sender,KeyboardFocusChangedEventArgs e)
{
textBox1.Text =((FrameworkElement )e.NewFocus).Name;
}


I have a search screen in my WPF application. The screen is implemented as a UserControl in a TabItem of a TabControl. When the user switches to the Search tab, I want the focus to go into one particular field.

So I added a Loaded event handler to the UserControl tag in the Xaml and I called the Focus method of the control I want to have the initial focus in the Loaded event handler. This worked great until I upgraded the Telerik control library I'm using today. Now, when I switch to the Search tab, the focus is NOT in the field I want to have it, but I can't tell what control does have the focus.

The field I want to have focus already has GotFocus & LostFocus event handlers for other reasons. I remembered that in Win Forms, the LostFocus event handler arguments tell you which control is going to get the focus. So I put a breakpoint in my LostFocus handler & discovered that the arguments to the LostFocus event handler in WPF don't include that information.

How can I figure out where the focus is going without putting GotFocus handlers on every control in my UserControl?

Tony

解决方案

You can try putting your breakpoint on the LostKeyboardFocus Attached Event instead of the LostFocus Event. It uses the KeyboardFocusChangedEventArgs Class which does have properties that show which element had focus and where the focus is going.

private void textBox1_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    textBox1.Text = ((FrameworkElement)e.NewFocus).Name ; 
}

这篇关于我如何找出焦点在我的WPF应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆