繁体   English   中英

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

[英]Close Window without code-behind in WPF

是否可以将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();
}

谢谢!

如果要关闭对话框Window ,可以添加Button 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" ... />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM