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

时间:2011-03-04 12:35:28

标签: c# wpf button user-interface

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

6 个答案:

答案 0 :(得分:12)

只需通过按钮调用close()功能:

WPF:

<Button Name="CloseButton" Content="x" Click="CloseButton_Click" />

代码隐藏:

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

答案 1 :(得分:2)

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

代码将是这样的:

Button Command="{Binding MainCloseButtonCommand}"
CommandParameter="{Binding ElementName=mainWindow}"

private void performMainCloseButtonCommand(object Parameter)
{
    Window objWindow  = Parameter as Window;
    objWindow.Close();
}

答案 2 :(得分:1)

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

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执行此操作,它可能如下所示:

<Button Name="closeButton" Click="closeButton_Click" />

答案 3 :(得分:1)

如果您想要关闭对话框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();
    }
}

Window中使用如下:

<Window x:Class="MyProjectNamespace.MainWindow" 
        xmlns:local="clr-namespace:MyProjectNamespace">

    <Button Name="CloseButton"
            local:ButtonBehavior.IsClose="True" ... />

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

答案 4 :(得分:0)

实际上就是这样:

<Window Name = "Chrome">
   .
   .
  <Button Name="closeButton" onClick="terminateApplication"/>
   .
</Window>

并在CS文件中

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

答案 5 :(得分:0)

在viewmodel中使用关闭按钮。视图模型在GUI上不依赖。

namespace YourLibrary.ComponentModel
{
   /// <summary>
  /// Defines Close method. Use for window, file stream,.... 
  /// </summary>
  public interface IClosable
  {
      /// <summary>
      /// Close of instance (window, file stream,... etc).
      /// </summary>
      void Close();
  }

}

MyWindow.xaml

  <Window  ...
       x:Name="ThisInstance"   
       ...
   >


   <Button Command="{Binding ButtonCommand}" CommandParameter="{Binding ElementName=ThisInstance}">

MyWindow.xaml.cs

public partial class MyWindow : Window, YourLibrary.ComponentModel.IClosable
{
 ....
}

MyViewModel.cs

public class MyViewModel 
{
  ICommand buttonCommand;
  /// <summary>
  /// Command for Button.
  /// Default action is close the window.  
  /// Close window via retyping parameter as <see cref="IClosable"/> 
  /// </summary>
  public ICommand ButtonCommand => buttonCommand ?? (buttonCommand=new RelayCommand(ButtonCommandExecute));
  void ButtonCommandExecute (object obj) 
  {
      var myWindow = (IClosable)obj;
      myWindow.Close();
  };

测试,在控制台中使用VIEWMODEL

 class Program
 {
    public class ConsoleWindow : YourLibrary.ComponentModel.IClosable
    {
        public void Close()
        {
            Console.WriteLine("Closing area...");
        }
    }


    static void Main(string[] args)
    {
        var program = new Program();
        program.DoMain(args);
    }

    public void DoMain(string[] args)
    {
        var consoleWindow = new ConsoleWindow();
        var viewModel = new MyViewModel()
        viewModel.ButtonCommand.Execute(consoleWindow);
    }
 }