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

问题描述 投票:3回答:1

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

我是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模式的问题的正确方法是什么。任何指向正确方向的人都将不胜感激!

c# wpf mvvm mvvm-light
1个回答
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

/// <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}"
© www.soinside.com 2019 - 2024. All rights reserved.