关闭WPF中没有代码隐藏的窗口

时间:2014-04-03 06:38:13

标签: c# wpf xaml button

是否可以绑定Button以关闭Window而无需添加代码隐藏事件?

<Button Content="OK" Command="{Binding CloseWithSomeKindOfTrick}" />

而不是以下XAML:

<Button Content="OK" Margin="0,8,0,0" Click="Button_Click">

使用代码隐藏:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Close();
}

谢谢!

1 个答案:

答案 0 :(得分:5)

如果要关闭对话框Window,可以添加按钮IsCancel属性:

<Button Name="CloseButton"
        IsCancel="True" ... />

这意味着以下MSDN

  

当您将Button的IsCancel属性设置为true时,您将创建一个使用AccessKeyManager注册的Button。 当用户按下ESC键时,该按钮被激活。

现在,如果您单击此按钮,或按 Esc ,则对话框Window即将关闭,但它对普通MainWindow不起作用。

要关闭MainWindow,您只需添加一个已经显示的Click处理程序。但是如果你想要一个更优雅的解决方案来满足MVVM风格,你可以添加附加行为:

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" ... />
相关问题