EventToCommand 与 InputBindings 问题
我创建了解决方案来重现我在使用 MVVM-Light EventToCommand 与 InputBindings 时遇到的问题。问题围绕一个窗口打开另一个窗口,如果我有一个输入绑定连接到转义键并关闭第二个视图,它会关闭第二个视图并返回到第一个视图。如果我使用 EventToCommand,然后手动调用关闭第二个视图的相同命令,它也会关闭第一个视图。
我预计如果没有代码就很难看到,因此我创建了一个测试解决方案来重现该问题。
步骤如下:
按预期工作
1) 单击第一个窗口的按钮打开第二个窗口。
2) 按第二个窗口上的转义键使用输入绑定
问题案例
1) 单击第一个窗口的按钮打开第二个窗口。
2)点击“你好”文本框 3) 按Escape 键使用EventToCommand 路径并且两个窗口都会关闭吗?
I've created solution to reproduce a problem that I'm having with MVVM-Light EventToCommand vs InputBindings. The issue revolves around one window opening another and if I have an InputBinding connected say to the escape key and close the second view, it closes the second view and returns to the first. If I use instead the EventToCommand and then manually call the same command it closed the second view, it also closes the first.
I expect it is a little hard to see without code so I've create a test solution to reproduce the problem.
The Steps are as follows:
Works as expected
1) Click the button the first window to open the second.
2) Press the escape key on the second to use the input bindings
Problem Case
1) Click the button the first window to open the second.
2) Click the "Hello" text box
3) Press the Escape key to use the EventToCommand path and both windows close?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须通知 WPF 事件处理机制,按钮按下已在您的事件处理程序中处理,并且不应在事件链中向上冒泡。如果不这样做,您的文本框将在活动窗口 (window2) 上调用 close,并且转义处理程序将在活动窗口上调用 close(window1,因为 window2 已被文本框的转义处理程序关闭)。因此,如果您按如下方式修改 Close2 函数,则一切正常:
You have to notify the WPF eventhandling mechanism that the button press was handled in your event handler and that it should not be bubbled up the event chain. If you don't your text box is calling close on the active window (window2) and the escape handler is calling close on the active window (window1 as window2 was already closed by the escape handler of the text box). So if you modify your Close2 function as follows everything works fine:
我认为问题是因为您在 EventToCommand 侦听器中挂钩了 PreviewKeyDown 事件。我认为它是在 KeyUp 和 KeyPress 事件触发之前对按键按下并关闭窗口做出反应。这意味着 KeyUp 和 KeyPress 将在主窗口上触发,主窗口会通过关闭做出反应。
我在示例中将 EventName 更改为 PreviewKeyPress,这似乎解决了问题。我可以按 Esc 键并让它仅关闭顶部窗口。
I think the issue is because of your hooking the PreviewKeyDown event in the EventToCommand listener. I think it is reacting to the key going down and closing the window before the KeyUp and KeyPress events fire. This means that KeyUp and KeyPress are going to fire on the main window, which reacts by closing.
I changed the EventName to PreviewKeyPress in your sample, and that seemed to fix the issue. I was able to press Escape and have it only close the top window.