2

私はWPFとMVVMLightフレームワークを使用しています(これらを使用するのは初めてです)。

私は次のことをしたい:

  1. ユーザーが「X」閉じるボタンをクリックすると、アプリケーションを終了するかどうかの確認ウィンドウを表示したいと思います。
  2. はいの場合、アプリケーションは閉じます
  3. いいえの場合、何も起こらず、通常どおりアプリケーションを使用できます。

これまでのところ、私はこれを持っています:

  • MainWindow.xaml.csの場合:

    public MainWindow()
    {
        InitializeComponent();
        Closing += (s, e) => ViewModelLocator.Cleanup();
    }
    
  • ViewModelLocator.csの場合:

    public static void Cleanup()
    {
        ServiceLocator.Current.GetInstance<MainViewModel>().Cleanup();
    }
    
  • MainViewModel.csの場合:

    public override void Cleanup()
    {
        MessageBoxResult result = MessageBox.Show(
                        "Unsaved data will be lost, would you like to exit?",
                        "Confirmation",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);
    
        if (result == MessageBoxResult.Yes)
        {
          // clean-up resources and exit
        }
        else
        {
          // ????
        }
    

実際、ユーザーが「はい」または「いいえ」と答えると、どちらの場合もアプリケーションは終了します。

ここから先に進む方法がよくわかりません...

どんな助けでも素晴らしいでしょう!

ありがとう

4

2 に答える 2

5

EventToCommandクロージングをキャンセルする場合は、 inを使用しEventTriggerてクロージングイベントをキャッチしCancel、passedのプロパティCancelEventArgsをtrueに設定できます。

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;
      } 
   }
}
于 2013-01-18T09:32:05.813 に答える
2

Closingイベント引数には、ユーザーがクローズをキャンセルした場合Cancelに設定する必要のあるプロパティがあります。trueしたがって、Cleanup()メソッドが返さboolれ、それをプロパティに割り当てる必要がありCancelます。

于 2013-01-18T09:11:22.447 に答える