WPF和最初的重点 [英] WPF and initial focus

查看:192
本文介绍了WPF和最初的重点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来WPF应用程序启动时没有任何焦点。



这真的很奇怪。我用过的其他所有框架都只是你所期望的:把最初的焦点放在按Tab键顺序的第一个控件上。但我已经确认它是WPF,不只是我的应用程序 - 如果我创建一个新的窗口,只是把一个文本框,并运行应用程序,文本框没有焦点,直到我点击它或按Tab 。 Yuck。



我的实际应用程序比TextBox更复杂。 UserControls中有几个UserControls层。其中一个UserControls有Focusable =True和KeyDown / KeyUp处理程序,并且我希望在我的窗口打开后它就有了焦点。我仍然有点WPF新手,但我没有太多的运气搞清楚如何做到这一点。



如果我启动我的应用程序,然后按Tab键,然后焦点转到我的可对焦控制,并开始按我想要的方式工作。但是我不希望我的用户在开始使用该窗口之前必须点击Tab。



我已经使用了FocusManager.FocusedElement,但是我不知道要设置哪个控件(顶层Window?包含可聚焦控件的父级?可聚焦控件本身?)或将其设置为什么。



一旦窗口打开,我需要做些什么才能使我的深层嵌套控件具有初始焦点?或者更好的办法是将第一个可调焦的控件集中到tab键顺序中?

解决方案

查看Focusable属性的使用位置,并找到了解决方案。我只需要添加下面的代码到我的窗口的构造函数:

  Loaded + =(sender,e)=> 
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

这会自动选择第一个控件的顺序,所以这是一个通用的解决方案,应该可以被放到任何窗口,只要工作。


It seems that when a WPF application starts, nothing has focus.

This is really weird. Every other framework I've used does just what you'd expect: puts initial focus on the first control in the tab order. But I've confirmed that it's WPF, not just my app -- if I create a new Window, and just put a TextBox in it, and run the app, the TextBox doesn't have focus until I click on it or press Tab. Yuck.

My actual app is more complicated than just a TextBox. I have several layers of UserControls within UserControls. One of those UserControls has Focusable="True" and KeyDown/KeyUp handlers, and I want it to have the focus as soon as my window opens. I'm still somewhat of a WPF novice, though, and I'm not having much luck figuring out how to do this.

If I start my app and press the Tab key, then focus goes to my focusable control, and it starts working the way I want. But I don't want my users to have to hit Tab before they can start using the window.

I've played around with FocusManager.FocusedElement, but I'm not sure which control to set it on (the top-level Window? the parent that contains the focusable control? the focusable control itself?) or what to set it to.

What do I need to do to get my deeply-nested control to have initial focus as soon as the window opens? Or better yet, to focus the first focusable control in the tab order?

解决方案

I had the bright idea to dig through Reflector to see where the Focusable property is used, and found my way to this solution. I just need to add the following code to my Window's constructor:

Loaded += (sender, e) =>
    MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

This will automatically select the first control in the tab order, so it's a general solution that should be able to be dropped into any window and Just Work.

这篇关于WPF和最初的重点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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