如果要关闭对话框Window,可以为Button添加IsCancel属性:
<Button Name="CloseButton"
IsCancel="True" ... />
这表示以下MSDN:
当您将 Button 的 IsCancel 属性设置为 true 时,您将创建一个向 AccessKeyManager 注册的 Button。 当用户按下 ESC 键时,按钮就会被激活。
现在,如果您单击此按钮,或按 Esc,则对话框 Window 正在关闭,但它不适用于普通的 MainWindow。
要关闭MainWindow,您可以简单地添加一个已经显示的 Click 处理程序。但是如果你想要一个更优雅的解决方案来满足 MVVM 风格,你可以添加 attached 行为:
public static class ButtonBehavior
{
#region Private Section
private static Window MainWindow = Application.Current.MainWindow;
#endregion
#region IsCloseProperty
public static readonly DependencyProperty IsCloseProperty;
public static void SetIsClose(DependencyObject DepObject, bool value)
{
DepObject.SetValue(IsCloseProperty, value);
}
public static bool GetIsClose(DependencyObject DepObject)
{
return (bool)DepObject.GetValue(IsCloseProperty);
}
static ButtonBehavior()
{
IsCloseProperty = DependencyProperty.RegisterAttached("IsClose",
typeof(bool),
typeof(ButtonBehavior),
new UIPropertyMetadata(false, IsCloseTurn));
}
#endregion
private static void IsCloseTurn(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
if (MainWindow != null)
MainWindow.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
var button = sender as Button;
if (button != null)
button.Click += new RoutedEventHandler(button_Click);
}
}
private static void button_Click(object sender, RoutedEventArgs e)
{
MainWindow.Close();
}
private static void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
MainWindow.Close();
}
}
在MainWindow 中使用这种行为,如:
<Window x:Class="MyProjectNamespace.MainWindow"
xmlns:local="clr-namespace:MyProjectNamespace">
<Button Name="CloseButton"
local:ButtonBehavior.IsClose="True" ... />