これを行う方法の1つは、DialogServiceのようなサービスを実装してViewModelに注入し、コマンドが実行されたときに呼び出すことです。これにより、ビューとアプリケーションのロジックを切り離すことができ、ViewModelはダイアログの実際の表示方法を完全に知らず、すべての作業をサービスに委任します。ここに例があります。
まずあなたがダイアログを表示し、その結果を返すのすべての作業を処理し、ダイアログサービスの作成:次に、あなたはViewModelににそのサービス上のあなたのViewModelには依存させるとinjectそれ
public interface IDialogService
{
bool ConfirmDialog(string message);
}
public bool ConfirmDialog(string message)
{
MessageBoxResult result = MessageBox.Show(message, "Confirm", MessageBoxButton.YesNo, MessageBoxImage.Question);
return result == MessageBoxResult.Yes ? true : false;
}
を:
public class MyViewModel : ViewModelBase
{
private readonly IDialogService _dialogService;
public MyViewModel(IDialogService dialogService)
{
_dialogService = dialogService;
}
}
最後に、コマンドでサービスを呼び出して、ユーザーがレコードを削除するかどうかを絶対に確認するかどうかを確認します。
public Command DeleteRecordsCommand
{
get
{
if (_deleteRecordsCommand == null)
{
_deleteRecordsCommand = new Command(
() =>
{
if (_dialogService.ConfirmDialog("Delete records?"))
{
// delete records
}
}
);
}
return _deleteRecordsCommand;
}
}
あなたのアプローチは面倒ですが、それほど良くありません。いくつかのMessageBoxを試してください – Ramankingdom
'Click'のeventHandlerで' MessageBox'を使い、ViewModelのCommandを使ってvm.DeleteRowsCommand.Execute(someObjectIfYouNeedIt)のように実行してください。 – XAMlMAX