我正在扩展控件画布并为MouseEvents添加我自己的自定义覆盖。我很想知道为什么这个基本的覆盖,当用户按下键盘上的任何键时它不会发出信号。如何在wpf c#?
中使这个覆盖工作namespace CanvasGraphDemo
{
public class CanvasGraph : Canvas
{
public CanvasGraph()
{
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
Console.WriteLine("context menu open");
e.Handled = true;
}
}
}
}
答案 0 :(得分:3)
这将适用于您的具体示例。正如其他人所指出的那样,你必须使Canvas
具有焦点并实际关注它,因此它将接收键盘事件。
public class CanvasGraph : Canvas
{
public CanvasGraph()
{
Focusable = true;
Loaded += OnCanvasGraphLoaded;
}
private void OnCanvasGraphLoaded(object sender, RoutedEventArgs routedEventArgs)
{
Focus();
Loaded -= OnCanvasGraphLoaded;
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
Console.WriteLine("context menu open");
e.Handled = true;
}
}
}