单击“取消”按钮(或右上角的 X,或 Esc)后如何取消从特定表单退出?
WPF:
<Window
...
x:Class="MyApp.MyView"
...
/>
<Button Content="Cancel" Command="{Binding CancelCommand}" IsCancel="True"/>
</Window>
视图模型:
public class MyViewModel : Screen {
private CancelCommand cancelCommand;
public CancelCommand CancelCommand {
get { return cancelCommand; }
}
public MyViewModel() {
cancelCommand = new CancelCommand(this);
}
}
public class CancelCommand : ICommand {
public CancelCommand(MyViewModel viewModel) {
this.viewModel = viewModel;
}
public override void Execute(object parameter) {
if (true) { // here is a real condition
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(
"Really close?", "Warning",
System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.No) { return; }
}
viewModel.TryClose(false);
}
public override bool CanExecute(object parameter) {
return true;
}
}
当前代码不起作用。如果用户在弹出对话框中选择“否”,我希望用户保留当前表单。
此外,重写 CanExecute 也没有帮助。它只是禁用该按钮。我想允许用户点击按钮,但随后通知他/她,数据将丢失。
也许我应该在按钮上分配一个事件侦听器?
EDIT:
我设法在“取消”按钮上显示弹出窗口。但我仍然无法管理 Esc 或 X 按钮(右上角)。看来我对取消按钮感到困惑,因为当我单击 X 按钮或 Esc 时会执行 Execute 方法。
EDIT2:
我改变了问题。这是“如何取消取消按钮”。然而,这不是我想要的。我需要取消 Esc 或 X 按钮。
在“MyViewModel”中我添加:
protected override void OnViewAttached(object view, object context) {
base.OnViewAttached(view, context);
(view as MyView).Closing += MyViewModel_Closing;
}
void MyViewModel_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
if (true) {
MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(
"Really close?", "Warning",
System.Windows.MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.No) {
e.Cancel = true;
}
}
}
这解决了我的问题。但是,我需要 ICommand 来了解单击了哪个按钮,“保存”或“取消”。有什么办法可以消除事件的使用吗?