在WPF MVVM中处理窗口关闭按钮

20

有没有一种方法可以通过绑定到命令或覆盖window.close命令来处理视图模型中的窗口关闭按钮(即右上角的“X”)?这样,关闭一个窗口会返回到上一个窗口。谢谢。


这回答解决了你的问题吗?如何在WPF表单中捕获窗口关闭按钮(位于窗口右上角的红色X按钮)的事件? - StayOnTarget
2个回答

35

有几种方法可以做到这一点。我在下面指出了两种方法。

  1. 您可以使用附加命令将关闭按钮绑定到视图模型中。

  2. 您可以使用以下代码:

Xaml:

<Window x:Class="WpfInfragisticsModal.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" 
        xmlns:ig="http://schemas.infragistics.com/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        Name="myWindow">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closing">
            <i:InvokeCommandAction Command="{Binding CloseWindowCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
    </Grid>
</Window>

注意:添加 System.Windows.Interactivity 引用

视图模型

private ICommand closeWindowCommand;

public ICommand CloseWindowCommand
{
      get
      {
          if (closeWindowCommand == null)
          {
             closeWindowCommand = new RelayCommand(param => this.CloseWindow(), null);
          }
          return closeWindowCommand;
      }
 }

private void CloseWindow()
{
     //Do your operations
}

这是我的RelayCommand类。

public class RelayCommand : ICommand
{
    /// <summary>
    /// Initializes a new instance of the <see cref="RelayCommand"/> class.
    /// </summary>
    /// <param name="execute">The execute.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="RelayCommand"/> class.
    /// </summary>
    /// <param name="execute">The execute.</param>
    /// <param name="canExecute">The can execute.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Defines the method that determines whether the command can execute in its current state.
    /// </summary>
    /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
    /// <returns>
    /// true if this command can be executed; otherwise, false.
    /// </returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    /// <summary>
    /// Occurs when changes occur that affect whether or not the command should execute.
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Defines the method to be called when the command is invoked.
    /// </summary>
    /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    /// <summary>
    /// Action
    /// </summary>
    private readonly Action<object> _execute;


    /// <summary>
    /// Predicate
    /// </summary>
    private readonly Predicate<object> _canExecute;
}

就是这样,MVVM Light 可以帮助你解决问题! - Tom Kerkhove
谢谢Haritha,我尝试过了,但是没用,我找不到“system.windows.interactivity”命名空间... 我正在使用VS2010..有人建议使用“windowsbase”,但即使这样,也无法让xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"正常工作... - Andris Mudiayi
1
你好Andris, 你需要安装一个可再分发的程序才能在Visual Studio中看到它。 你可以在这里下载它:http://www.microsoft.com/en-us/download/details.aspx?id=10801。 - Haritha
2
好的,“Closing”是“Window”事件,在窗口关闭之前触发,这与“X按钮单击”不同,因为可以通过“Window.Close()”在代码的任何位置关闭窗口。因此,如果需要将UI关闭窗口与代码关闭分开(例如-自定义InputDialog),那就非常困难了,我现在看不到任何解决方案。 - oxfn
1
жңүдёҖдёӘз”ЁдәҺExpression SDKзҡ„NuGetеҢ…Install-Package Expression.Blend.SdkпјҢд»ҘйҳІе…¶д»–дәәйҒҮеҲ°зјәе°‘.dllж–Ү件зҡ„й—®йўҳгҖӮ - Henrik Bøgelund Lavstsen
@oxfn:完全正确!在我看来,尽管WPF具有可能过度设计的自定义选项,但它的一个主要缺点是没有内置的方法可以直接绑定到窗口关闭按钮,而是通过Window.Closing 事件间接绑定。正如你所指出的那样,即使调用了Window.Close方法,后者也会被触发,这将是一个问题,如果代码(在我认为非常普遍的情况下)需要将窗口关闭按钮与“取消”按钮相同对待,但Window.Closing 事件也被处理程序引发,例如“确定”/“选择”按钮。 - Tom

1
问题在于我关闭了一个父窗口,并在关闭其相应的子窗口后重新打开它,导致内存泄漏。我通过隐藏父窗口,然后在子窗口关闭后再次显示它来解决问题。我是wpf和windows开发的新手,所以我边学边做。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接