我希望处理窗口的Closing
事件(当用户单击右上角的'X‘按钮时),以便最终显示确认消息或/和取消关闭。
我知道如何在代码隐藏中做到这一点:订阅窗口的Closing
事件,然后使用CancelEventArgs.Cancel
属性。
但是我使用的是MVVM,所以我不确定这是不是一个好的方法。
我认为最好的方法是将Closing
事件绑定到我的ViewModel中的Command
。
我试过了:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<cmd:EventToCommand Command="{Binding CloseCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
在我的ViewModel中有一个关联的RelayCommand
,但是它不工作(命令的代码不会被执行)。
发布于 2010-09-10 17:42:03
我很想在您的App.xaml.cs文件中使用一个事件处理程序,它允许您决定是否关闭应用程序。
例如,您可以在App.xaml.cs文件中包含类似以下代码的内容:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Create the ViewModel to attach the window to
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
// Create the handler that will allow the window to close when the viewModel asks.
EventHandler handler = null;
handler = delegate
{
//***Code here to decide on closing the application****
//***returns resultClose which is true if we want to close***
if(resultClose == true)
{
viewModel.RequestClose -= handler;
window.Close();
}
}
viewModel.RequestClose += handler;
window.DataContaxt = viewModel;
window.Show();
}
然后,在您的MainWindowViewModel代码中,您可以拥有以下内容:
#region Fields
RelayCommand closeCommand;
#endregion
#region CloseCommand
/// <summary>
/// Returns the command that, when invoked, attempts
/// to remove this workspace from the user interface.
/// </summary>
public ICommand CloseCommand
{
get
{
if (closeCommand == null)
closeCommand = new RelayCommand(param => this.OnRequestClose());
return closeCommand;
}
}
#endregion // CloseCommand
#region RequestClose [event]
/// <summary>
/// Raised when this workspace should be removed from the UI.
/// </summary>
public event EventHandler RequestClose;
/// <summary>
/// If requested to close and a RequestClose delegate has been set then call it.
/// </summary>
void OnRequestClose()
{
EventHandler handler = this.RequestClose;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
#endregion // RequestClose [event]
https://stackoverflow.com/questions/3683450
复制相似问题