wpf设置焦点问题
你好 我无法将焦点集中在控制父级上。我有一个放置在画布上的控件。 如果我单击该控件,我需要将焦点设置在画布上才能处理一些键盘事件。 然而,尽管我试图将焦点设置为
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseDown(e);
Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
designer.Focus() ;//this doesn't work
Keyboard.Focus(designer); //this also doesn't work
}
附加到画布的键盘事件不会触发。
Hi
I'm not able to set focus on parent of control. I have a control which is placed on canvas.
If I click that control I need to set focus on canvas in order to handle some keyboard events.
However despite the fact that I was trying to set focus like that
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseDown(e);
Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
designer.Focus() ;//this doesn't work
Keyboard.Focus(designer); //this also doesn't work
}
Keyboard events which are attached to canvas don't fire.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保画布具有可聚焦和IsEnabled 均设置为 true。否则,Focus() 将失败。来自 Focus() 文档:
此外,由于您是在 PreviewMouseDown 事件中执行此操作,因此您可能需要按如下方式重新设计您的方法:
Make sure that the Canvas has Focusable and IsEnabled both set to true. Without that, Focus() will fail. From Focus() docs:
In addition, since you're doing this in a PreviewMouseDown event, you may need to rework your method as follows:
使用 FocusManager 将画布设置为焦点范围。这里有一个很好的示例说明如何执行此操作: 可以' t 将焦点设置到 UserControl 的子级。
Use the FocusManager to set the canvas as a focus scope. There is a good example of how to do this here: Can't set focus to a child of UserControl.
我使用 My UserControl 的属性:Background="Transparent"。
I use My UserControl with attribute: Background="Transparent".