如果您總是需要在關閉時保存,爲什麼不從Close中調用Save()方法)方法在ViewModel中而不是從視圖?然後確保該窗口只從ViewModel關閉,而不是從View本身關閉。像(未經測試,但你明白了)
public class SaveOnCloseViewModel
{
public event Action RequestClose;
...
public void Close()
{
Save();
RequestClose();
}
}
public class SaveOnCloseView
{
private SaveOnCloseViewModel _vm;
public SaveOnCloseView(SaveOnCloseViewModel vm)
{
_vm = vm;
_vm.RequestClose += this.PerformClose;
this.OnClosing += Window_Closing;
}
private bool _isClosing = false;
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_isClosing)
{
e.Cancel = true;
_vm.Close();
}
}
private void PerformClose()
{
_isClosing = true;
this.Close();
}
}
這對我有效....謝謝:) – 2010-06-28 08:00:27