我正在使用 WPF 和 MVVM Light 框架(我是新使用它们的)。
我想做以下事情:
- 当用户单击“X”关闭按钮时,我想显示一个确认窗口,以确定他是否要退出应用程序。
- 如果是,则应用程序关闭
- 如果否,则不会发生任何事情,他仍然可以正常使用该应用程序
到目前为止,我有这个:
-
在 MainWindow.xaml.cs 中:
public MainWindow()
{
InitializeComponent();
Closing += (s, e) => ViewModelLocator.Cleanup();
}
-
在 ViewModelLocator.cs 中:
public static void Cleanup()
{
ServiceLocator.Current.GetInstance<MainViewModel>().Cleanup();
}
-
在 MainViewModel.cs 中:
public override void Cleanup()
{
MessageBoxResult result = MessageBox.Show(
"Unsaved data will be lost, would you like to exit?",
"Confirmation",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// clean-up resources and exit
}
else
{
// ????
}
实际上,如果用户回答“是”或“否”,在这两种情况下应用程序都会退出。
我不太确定如何从这里继续......
任何帮助都会很棒!
Thanks
您可以使用EventToCommand
in an EventTrigger
捕捉结束事件并设置Cancel
过去的财产CancelEventArgs
如果您想取消关闭,则为 true:
XAML:
<Window ...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF45"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding OnClosingCommand}"
PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid>
...
</Grid>
</Window>
视图模型:
public class MainViewModel : ViewModelBase
{
public RelayCommand<CancelEventArgs> OnClosingCommand { get; set; }
public MainViewModel()
{
this.OnClosingCommand =
new RelayCommand<CancelEventArgs>(this.OnClosingCommandExecuted);
}
private void OnClosingCommandExecuted(CancelEventArgs cancelEventArgs)
{
...
if (mustCancelClosing)
{
cancelEventArgs.Cancel = true;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)