Close window without code in WPF

Is it possible to bind Buttonto closing Windowwithout adding events with code?

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

Instead of the following XAML:

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

With code:

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

Thank!

+4
source share
1 answer

If you want to close the dialog box Window, you can add the Button property IsCancel:

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

This means the following MSDN:

When you set the IsCancelbutton property to true, you create the button registered with AccessKeyManager. Then the button is activated when the user presses the ESC key.

, 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" ... />
+4

Source: https://habr.com/ru/post/1534763/


All Articles