ウィンドウのイベントAttached behavior
を処理し、 fromを実行し、パラメーターとして true または false を返す と を記述して、VM がウィンドウの終了を停止したい場合に終了イベントをキャンセル ( ) できるようにすることができます。Window.Closing()
ClosingCommand
ViewModel
e.Cancel
以下のコードはコンセプト用であり、完全ではありません
XAML
<Window x:Class="..."
...
myBheaviors:WindowBehaviors.ClosingCommand="{Binding MyClosingCommand}">
...
</Window>
ビューモデル
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
。ウィンドウのビューモデルには、ユーザー コントロールのビューモデルが含まれている必要があります。そのため、Closing
イベントの IsDirty() 呼び出しは、UserControls の ViewModel も精査できます。