单击取消按钮(或右上角的X或Esc)后,如何取消退出特定表单?
WPF:
<Window
...
x:Class="MyApp.MyView"
...
/>
<Button Content="Cancel" Command="{Binding CancelCommand}" IsCancel="True"/>
</Window>
ViewModel:
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类中执行View的工作。让您的View类处理关闭请求以及是否应取消它。
要取消关闭窗口,您可以订阅Closing
view事件,并CancelEventArgs.Cancel
在显示之后将其设置为true MessageBox
。
这是一个例子:
<Window
...
x:Class="MyApp.MyView"
Closing="OnClosing"
...
/>
</Window>
后面的代码:
private void OnClosing(object sender, CancelEventArgs e)
{
var result = MessageBox.Show("Really close?", "Warning", MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
{
e.Cancel = true;
}
// OR, if triggering dialog via view-model:
bool shouldClose = ((MyViewModel) DataContext).TryClose();
if(!shouldClose)
{
e.Cancel = true;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句