【问题标题】:Close Window without code-behind in WPF在 WPF 中关闭没有代码隐藏的窗口
【发布时间】:2014-05-14 19:31:38
【问题描述】:

是否可以在不添加代码隐藏事件的情况下绑定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();
}

谢谢!

【问题讨论】:

标签: c# wpf xaml button


【解决方案1】:

如果要关闭对话框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" ... />

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多