开发者

EventToCommand vs InputBindings Problem

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开发者_JAVA百科 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?

Example Solution


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:

    public void Close2(KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
            Close();
        e.Handled = true;
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜