如何在wpf MVVM中正确处理窗口的关闭事件

时间:2015-08-03 08:42:34

标签: c# wpf mvvm mvvm-light

我知道这个问题已被多次询问,但我会尽量具体说明。

我是WPF / MVVM的初学者,在我的项目中使用Galasoft的MVVM Light Toolkit。

我有一个视图,其中包含用户输入一些患者详细信息的表单。当他们点击关闭(X)按钮时,我想检查他们是否输入了某些内容,如果是,请在关闭之前询问他们是否要保存(是,否和取消)选项。我做了一些研究,发现有很多人建议使用EventToCommand功能,

XAML

<Window
   xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
   xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF45"
   DataContext="{Binding Main, Source={StaticResource Locator}}">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="Closing">
         <cmd:EventToCommand Command="{Binding OnClosingCommand}" 
            PassEventArgsToCommand="True"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
...
</Window>

查看模型

public class MainViewModel : ViewModelBase
{
   public RelayCommand<CancelEventArgs> OnClosingCommand { get; set; }

   public MainViewModel()
   {
      this.OnClosingCommand = 
         new RelayCommand<CancelEventArgs>(this.OnClosingCommandExecuted);
   }

   private void OnClosingCommandExecuted(CancelEventArgs cancelEventArgs)
   {
      // logic to check if view model has updated since it is loaded
      if (mustCancelClosing)
      {
         cancelEventArgs.Cancel = true;
      } 
   }
}

以上示例取自Confirmation when closing window with 'X' button with MVVM light

然而,MVVM Light Toolkit本身的创建者说这打破了MVVM模式试图实现的关注点的分离,因为它传递了属于视图的事件参数(在这种情况下是CancelEventArgs )到视图模型。他在这篇文章中http://blog.galasoft.ch/posts/2014/01/using-the-eventargsconverter-in-mvvm-light-and-why-is-there-no-eventtocommand-in-the-windows-8-1-version/

这么说

所以我的问题是,处理这种不会破坏MVVM模式的问题的正确方法是什么。任何指向正确方向的人都会非常感激!

1 个答案:

答案 0 :(得分:2)

我不是假装绝对真理,但我喜欢以下方法 基本视图模型有RelayCommand / DelegateCommand,如下所示:

public ICommand ClosingCommand { get; }

其中ICommand.Execute实现为:

/// <summary>
/// Executes an action, when user closes a window, displaying this instance, using system menu.
/// </summary>
protected virtual void Closing()
{
}

ICommand.CanExecute as:

/// <summary>
/// Detects whether user can close a window, displaying this instance, using system menu.
/// </summary>
/// <returns>
/// <see langword="true"/>, if window can be closed;
/// otherwise <see langword="false"/>.
/// </returns>
protected virtual bool CanClose()
{
    return true;
}

反过来,UI使用附加行为来处理Window.Closing

public static class WindowClosingBehavior
{
    public static readonly DependencyProperty ClosingProperty = DependencyProperty.RegisterAttached(
            "Closing", 
            typeof(ICommand), 
            typeof(WindowClosingBehavior),
            new UIPropertyMetadata(new PropertyChangedCallback(ClosingChanged)));

    public static ICommand GetClosing(DependencyObject obj)
    {
        return (ICommand)obj.GetValue(ClosingProperty);
    }

    public static void SetClosing(DependencyObject obj, ICommand value)
    {
        obj.SetValue(ClosingProperty, value);
    }

    private static void ClosingChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        var window = target as Window;
        if (window != null)
        {
            if (e.NewValue != null)
                window.Closing += Window_Closing;
            else
                window.Closing -= Window_Closing;
        }
    }

    private static void Window_Closing(object sender, CancelEventArgs e)
    {
        var window = sender as Window;
        if (window != null)
        {
            var closing = GetClosing(window);
            if (closing != null)
            {
                if (closing.CanExecute(null))
                    closing.Execute(null);
                else
                    e.Cancel = true;
            }
        }
    }
}

XAML(假设,该视图模型是窗口的DataContext):

behaviors:WindowClosingBehavior.Closing="{Binding ClosingCommand}"