繁体   English   中英

C#WPF为另一个页面中的处理程序的窗口添加KeyUp事件

[英]C# WPF add KeyUp event for window with a handler in another page

我正在开发WPF项目,并且是我的新手。 我这样组织我的项目:

MainWindow.xaml         (Contains a NavigationWindow)
  MainWindow.xaml.cs
HomePage.xaml           (Contains a series of function)
  Homepage.xaml.cs

问题是我想在程序中添加一个KeyUp事件,并且希望它在按下某个键时调用HomePage.xaml.cs一个函数。 但是我发现不可能将KeyUp事件添加到Page对象,因此我决定将其添加到NavigationWindow 但是,我无法在NavigationWindow中访问HomePage.xaml.cs的函数,因此我想到了一个主意。

var window = Window.GetWindow(this);
((MainWindow) window).KeyUp += new system.Windows.Input.KeyEventHandler(this.Window_KeyUp);

但是,这不起作用并抛出System.NullReferenceException 我不知道为什么会这样。 也许它想说thisnull的? 但为什么?

虽然很傻,但我想亲自回答这个问题。 (顺便说一句,我还没有收到很多让我感到不安的答案。幸运的是我发现了问题)

问题是关于Window.GetWindow(this) 它返回null ,它显然没有KeyUp事件。 解决方案是将其更改为Application.Current.Windows ,它是Windows层次结构的数组。 因此Application.Current.Windows[0]可以返回MainWindow对象,该对象可以与处理程序一起附加。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM