【发布时间】:2016-07-07 20:43:25
【问题描述】:
单击“取消”按钮(或右上角的 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 也无济于事。它只是禁用按钮。我想让用户点击按钮,然后通知他/她,数据将丢失。 也许我应该在按钮上分配一个事件监听器?
编辑:
我设法在取消按钮上显示弹出窗口。但我仍然无法管理 Esc 或 X 按钮(右上角)。我似乎对取消按钮感到困惑,因为当我单击 X 按钮或 Esc 时会执行 Execute 方法。
编辑2:
我改变了问题。这是“如何取消取消按钮”。然而,这不是我想要的。我需要取消 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 来了解单击了哪个按钮、保存或取消。有没有办法消除事件的使用?
【问题讨论】:
-
您的
viewModel.TryClose(false)函数是否向您的视图发送事件以关闭对话框?如果是这样,您可以从 xaml 代码中删除IsCancel="true"。该部分导致表单关闭。 -
@qqww2 如果我删除 IsCancel="true" 然后如果我单击 Esc 它不会关闭窗口。我希望在 Esc 上关闭窗口。
-
注册一个
KeyBinding到你的命令。 Here 就是一个例子。
标签: c# wpf icommand cancellation