【问题标题】:Parent window handles the Keyup event from the child window in WPF父窗口处理来自 WPF 中子窗口的 Keyup 事件
【发布时间】:2012-08-13 06:50:30
【问题描述】:

父窗口设计为附加了 keyup 事件。 MainWindow 是这样的:

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_KeyUp(object sender, KeyEventArgs e)
    {
        if (e != null && e.Key == Key.Return)
        {
            MessageWindow msgWindow = new MessageWindow("KEY UP");
            msgWindow.Show();
        }
    }
}

MessageWindow 有一个 OK 按钮关闭窗口,如下所示:

public partial class MessageWindow : Window
{

    public MessageWindow()
    {
       InitializeComponent();
    }

    public MessageWindow(string message) : this()
    {
        txtMess.Text = message;
    }

    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
}

在父级接收到作为 [Return] 的输入键时,将初始化并显示一个新的子窗口。 按 T​​AB 聚焦 OK 按钮,然后按 Enter。 子 MessageWindow 再次弹出。

原因:当子窗口按下RETURN键关闭父窗口时,父窗口收到KeyUp事件。

请提供一种方法来停止父级处理 KeyUp 事件,而不是使用 FLAG。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    尝试使用 PreviewKeyDown 事件而不是 KeyUp 事件

    【讨论】:

    • 这个答案是正确的,但我想补充一点,这是因为 PreviewX 事件从根元素向下延伸到最嵌套的元素,而普通 X 事件从最嵌套的元素向上冒泡根元素。这意味着根元素获得了处理隧道事件的第一个机会和处理冒泡事件的最后机会。
    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多