首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用WPF / MVVM Light Toolkit处理窗口关闭事件

用WPF / MVVM Light Toolkit处理窗口关闭事件
EN

Stack Overflow用户
提问于 2010-09-10 17:18:04
回答 9查看 211.9K关注 0票数 152

我希望处理窗口的Closing事件(当用户单击右上角的'X‘按钮时),以便最终显示确认消息或/和取消关闭。

我知道如何在代码隐藏中做到这一点:订阅窗口的Closing事件,然后使用CancelEventArgs.Cancel属性。

但是我使用的是MVVM,所以我不确定这是不是一个好的方法。

我认为最好的方法是将Closing事件绑定到我的ViewModel中的Command

我试过了:

代码语言:javascript
运行
复制
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <cmd:EventToCommand Command="{Binding CloseCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

在我的ViewModel中有一个关联的RelayCommand,但是它不工作(命令的代码不会被执行)。

EN

Stack Overflow用户

发布于 2010-09-10 17:42:03

我很想在您的App.xaml.cs文件中使用一个事件处理程序,它允许您决定是否关闭应用程序。

例如,您可以在App.xaml.cs文件中包含类似以下代码的内容:

代码语言:javascript
运行
复制
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代码中,您可以拥有以下内容:

代码语言:javascript
运行
复制
#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]
票数 4
EN
查看全部 9 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3683450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档