WPF Button.IsCancel 属性如何工作? [英] How does the WPF Button.IsCancel property work?

查看:16
本文介绍了WPF Button.IsCancel 属性如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取消按钮背后的基本思想是使用 Escape Keypress 关闭窗口.

The basic idea behind a Cancel button is to enable closing your window with an Escape Keypress.

您可以将 IsCancel 属性设置为取消按钮为真,导致取消按钮自动关闭不处理 Click 的对话框活动.

You can set the IsCancel property on the Cancel button to true, causing the Cancel button to automatically close the dialog without handling the Click event.

来源:WPF 编程(Griffith,销售)

Source: Programming WPF (Griffith, Sells)

所以这应该有效

<Window>
<Button Name="btnCancel" IsCancel="True">_Close</Button>
</Window>

然而,我期望的行为并不适合我.父窗口是由 Application.StartupUri 属性指定的主应用程序窗口.什么有效

However the behavior I expect isn't working out for me. The parent window is the main application window specified by the Application.StartupUri property. What works is

<Button Name="btnCancel" IsCancel=True" Click="CloseWindow">_Close</Button>

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

  • IsCancel 的行为是否根据 Window 是普通窗口还是 Dialog 而有所不同?只有在调用 ShowDialog 时,IsCancel 才能像宣传的那样工作吗?
  • 按钮是否需要显式 Click 处理程序(IsCancel 设置为 true)才能在 Escape 按下时关闭窗口?
  • 推荐答案

    是的,它只适用于对话框,因为普通窗口没有取消"的概念,它与 WinForms 中从 ShowDialog 返回的 DialogResult.Cancel 相同.

    Yes, it only works on dialogs as a normal window has no concept of "cancelling", it's the same as DialogResult.Cancel returning from ShowDialog in WinForms.

    如果你想关闭一个带有转义的窗口,你可以在窗口上的 PreviewKeyDown 中添加一个处理程序,选择它是否是 Key.Escape 并关闭表单:

    If you wanted to close a Window with escape you could add a handler to PreviewKeyDown on the window, pickup on whether it is Key.Escape and close the form:

    public MainWindow()
    {
        InitializeComponent();
    
        this.PreviewKeyDown += new KeyEventHandler(CloseOnEscape);
    }
    
    private void CloseOnEscape(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
            Close();
    }
    

    这篇关于WPF Button.IsCancel 属性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆