在WPF中创建自定义关闭按钮

我是WPF / C#的新手,我正在考虑实现一个自定义窗口装饰器。 我需要创建一个关闭按钮,它基本上与关闭或x按钮完全相同,它出现在每个窗口的Windows应用程序的chrome上。

只需从按钮调用close()函数:

WPF:

  

后台代码:

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

如果您想使用MVVM体系结构,则可以将窗口名称作为命令参数传递,并在命令中关闭窗口。

代码将是这样的:

 Button Command="{Binding MainCloseButtonCommand}" CommandParameter="{Binding ElementName=mainWindow}" private void performMainCloseButtonCommand(object Parameter) { Window objWindow = Parameter as Window; objWindow.Close(); } 

如果您在当前视图中添加一个按钮,请从后面的代码中说出:

 var closeButton = new Button(); closeButton.Click += closeButton_Click; // Add the button to the window Content = closeButton; 

然后你可以响应事件,只需像这样调用Close()

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

这基本上做的是它为你的Window / UserControl添加一个按钮,当你按下它时,它将关闭窗口。

如果你从XAML这样做,它可能看起来像这样:

如果你想要关闭对话框Window的Button,可以为他添加IsCancel属性:

  

这意味着以下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(); } } 

Window使用如下:

   

现在可以通过单击按钮或按Esc关闭MainWindow ,这一切都独立于View (UI)。

实际上是这样的:

  . .  .  

在CS文件中

 private void terminateApplication(object sender, RoutedEventArgs e) { Chrome.Close(); } 

如果你有兴趣让这个按钮更漂亮,看看PrettyNSharp ,实际上有一个关闭按钮的例子,你可以非常容易地设计。