如何在wpf app关闭时显示消息框?

时间:2013-01-28 08:40:52

标签: wpf mvvm messagebox

我有一个带MVVM模式的WPF应用程序,它包含以下2个视图:

1:MainWindow.xaml(这是一个窗口) 以下是MainWindow.xaml的主要部分:

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:XliffListViewModel}">
        <vw:XliffListView />
    </DataTemplate>
</Window.Resources>
<Grid Margin="4">
    <Border Background="GhostWhite" BorderBrush="LightGray" BorderThickness="1" CornerRadius="5" >
        <ItemsControl ItemsSource="{Binding ViewModels}" Margin="4" />
    </Border>
</Grid>

2:XliffListView.xaml(这是用户控件)  XliffListView包含一个数据网格和一个用于保存所有发生的更改的按钮

我想在用户关闭应用时显示消息框,如果未保存更改

1 个答案:

答案 0 :(得分:0)

您可以编写和Attached behavior处理窗口Window.Closing()事件并从ClosingCommand执行ViewModel并返回true或false作为参数,以便可以取消( e.Cancel)如果VM想要阻止窗口关闭,则关闭事件。

以下代码仅用于概念而非完整

<强> XAML

  <Window x:Class="..."
          ...
          myBheaviors:WindowBehaviors.ClosingCommand="{Binding MyClosingCommand}">
      ...
  </Window>      

ViewModel

  public class MyWindowViewModel 
  {
      public ICommand MyClosingCommand
      {
          get
             { 
                 if (_myClosingCommand == null)
                    _myClosingCommand 
                       = new DelegateCommand<CancelEventArgs>(OnClosing);
                 return _myClosingCommand;
             }
      }

      private void OnClosing(CancelEventArgs e)
      {
          if (this.Dirty) //Some function that decides if the VM has pending changes.
              e.Cancel = true;
      }
  }

附加行为

  public static class WindowBehaviors
  {
      public static readonly DependencyProperty ClosingCommandProperty
         = DependencyProperty.RegistsrrAttached(
                "ClosingCommand", 
                ..., 
                new PropertyMetataData(OnClosingCommandChanged);

      public static ICommand GetClosingCommand(...) { .. };

      public static void SetClosingCommand(...) { .. };

      private static void OnClosingCommandChanged(sender, e)
      {
           var window = sender as Window;
           var command = e.NewValue as ICommand;
           if (window != null && command != null)
           {
               window.Closing 
                  += (o, args) => 
                     { 
                         command.Execute(args);
                         if (args.Cancel)
                         {
                             MessageBox.Show(
                                "Window has pending changes. Cannot close");

                             // Now window will be stopped from closing.
                         }
                     };     
           } 
      }
  }

修改

对于用户控件,而不是Closing使用Unloaded事件。

还尝试在ViewModel之间建立层次结构,即窗口的ViewModel应该包含UserControl的ViewModel。因此Closing事件的IsDirty()调用也可以仔细检查UserControls的ViewModel。