gpt4 book ai didi

c# - 设置焦点的wpf问题

转载 作者:太空狗 更新时间:2023-10-30 00:28:09 32 4
gpt4 key购买 nike

嗨我无法将焦点放在控制的父级上。我有一个放在 Canvas 上的控件。如果我单击该控件,我需要将焦点设置在 Canvas 上以处理一些键盘事件。然而,尽管事实上我正试图像那样设置焦点

 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


}

不会触发附加到 Canvas 的键盘事件。

最佳答案

确保 Canvas 有 FocusableIsEnabled都设置为真。没有那个,Focus()将失败。来自 Focus()文档:

To be focusable, Focusable and IsEnabled must both be true.

此外,由于您是在 PreviewMouseDown 事件中执行此操作,因此您可能需要按如下方式修改您的方法:

 protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
{
Canvas designer = VisualTreeHelper.GetParent(this) as Canvas;
designer.Focus() ;//this doesn't work
Keyboard.Focus(designer); //this also doesn't work

// Just in case something else is changing your focus as a result of a mouse event...
e.Handled = true;
base.OnPreviewMouseDown(e);
}

关于c# - 设置焦点的wpf问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3907328/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com