Confirmation when closing window with 'X' button with MVVM light

前端 未结 2 555
-上瘾入骨i
-上瘾入骨i 2021-01-03 13:26

I am using WPF and MVVM Light framework (I am new in using them).

I want to do the following:

  1. When the user click on the \'X\' close button, I want to
相关标签:
2条回答
  • You can use an EventToCommand in an EventTrigger to catch the closing event and set the Cancel property of the passed CancelEventArgs to true if you want to cancel the closing:

    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>
       <Grid>
         ...
       </Grid>
    </Window>
    

    ViewModel:

    public class MainViewModel : ViewModelBase
    {
       public RelayCommand<CancelEventArgs> OnClosingCommand { get; set; }
    
       public MainViewModel()
       {
          this.OnClosingCommand = 
             new RelayCommand<CancelEventArgs>(this.OnClosingCommandExecuted);
       }
    
       private void OnClosingCommandExecuted(CancelEventArgs cancelEventArgs)
       {
          ...
    
          if (mustCancelClosing)
          {
             cancelEventArgs.Cancel = true;
          } 
       }
    }
    
    0 讨论(0)
  • 2021-01-03 13:41

    The Closing event arguments have a Cancel property that you need to set to true if the user cancels the close. Therefore, your Cleanup() method should return bool and you should assign it to the Cancel property.

    0 讨论(0)
提交回复
热议问题