wpf 如何将焦点设置为 UserControl(使其可选)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15577697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set focus to UserControl (make it selectable)?
提问by Pavel Voronin
I need to set focus to UserControlitself, not its child.
Otherwise I cannot implement insertion from the buffer. :(
Setting Focusable=Truedoesn't help.
Google and SO tells only how to set focus to UserControl child.
我需要把焦点放在UserControl它自己身上,而不是它的孩子身上。
否则我无法实现从缓冲区插入。:(
设置Focusable=True没有帮助。Google 和 SO 只告诉如何将焦点设置到 UserControl 子项。
My control contains:
- Toolbar with several buttons bound to commands of the corresponding
VM
- TextBox which is the input for the filter
- DataGrid - list of items.
我的控件包含:
- 带有几个按钮的工具栏,绑定到相应 VM 的命令
- TextBox,它是过滤器的输入
- DataGrid - 项目列表。
I need to bind Ctrl+V command to VM. But to handle this gesture UserControlmust have focus within. When there are no items in the grid (VM's collection is empty) buttons are disabled and the only element which can get focus is TextBox. But it handles Ctrl+V in its own way and I don't want to change this behavior.
Thus, I need something to set focus to when I click the area of UserControl.
I believe UserControl is the best candidate for it.
But I don't know how to make it selectable.
我需要将 Ctrl+V 命令绑定到 VM。但要处理这个手势UserControl必须有重点。当网格中没有项目时(VM 的集合为空)按钮被禁用并且唯一可以获得焦点的元素是TextBox. 但它以自己的方式处理 Ctrl+V,我不想改变这种行为。
因此,当我单击 UserControl 区域时,我需要设置焦点。
我相信 UserControl 是它的最佳人选。
但我不知道如何使它可选择。
回答by Pavel Voronin
The whole problem was in my misunderstanding of controls' behavior.
This SO questionclearly shows it I believe.
整个问题在于我对控件行为的误解。
这个SO问题清楚地表明我相信。
Thus, setting UserControl.Focusable = trueis not sufficient. To make it navigatable via keyboard IsTabStopmust be truealso. And to make UC selectable by mouse click we should call Focus()in mouse eventhandler. That's it.
因此,设置UserControl.Focusable = true是不够的。要使其可通过键盘导航,也IsTabStop必须如此true。为了让 UC 可以通过鼠标点击来选择,我们应该调用Focus()鼠标事件处理程序。就是这样。

