通知View(Models)关闭程序

发布于 2024-10-08 09:06:38 字数 178 浏览 4 评论 0原文

所以我的 prism/mvvm/mef 程序运行良好,用户在应用程序中输入数据,然后关闭应用程序(或关闭计算机)。

如何让我的视图(模型)收到程序关闭/计算机关闭的通知,以便它可以保存用户数据或者询问是否应该保存这些数据?

在程序关闭时丢失数据绝对是需要避免的事情,并且在用户的每次按键时保存数据是没有意义的。

So I got my prism/mvvm/mef program running nicely along, the user is entering data in the application, then closes the application (or shuts down the computer).

How can I get my View(Model) notified of the program closing / the computer shutdown, so it can either save the users data or maybe ask if these should be saved?

Losing data on program close is definitely something to be avoided, and it does not make sense to save stuff on every single keypress of the user.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神妖 2024-10-15 09:06:38

我公开了客户端可以注册的 CompositeCommands 以获取有趣的全局“事件”,例如

public static class HostCommands
{
    private static readonly CompositeCommand Shutdown = new CompositeCommand();

    public static CompositeCommand ShutdownCommand
    {
        get { return Shutdown; }
    }
}

我在 shell 中触发关闭命令,例如

public Shell()
{
    InitializeComponent();

    Closing += (sender, e) =>
    {
        if (HostCommands.ShutdownCommand.CanExecute(e))
            HostCommands.ShutdownCommand.Execute(e);
    };
}

客户端可以按如下方式注册,例如

public SomeViewModel(IEventAggregator eventService)
{
    //blah, blah, blah...

    HostCommands.ShutdownCommand.
        RegisterCommand(new DelegateCommand<object>(_ => Save()));
}

更新

我不处理取消场景,但您可以通过传递给命令的对象来实现这一点。例如,在上面的代码中,我传入了一个 CancelEventArgs,客户端可以通过设置 Cancel=true 来操作它。在命令执行后,我可以在 Shell 关闭事件处理程序中检查此值,以得出是否应该取消关闭 shell。这种模式是可以扩展的。

I expose CompositeCommands that clients can register to for interesting global "events", e.g.

public static class HostCommands
{
    private static readonly CompositeCommand Shutdown = new CompositeCommand();

    public static CompositeCommand ShutdownCommand
    {
        get { return Shutdown; }
    }
}

I trigger the shutdown command in my shell, e.g.

public Shell()
{
    InitializeComponent();

    Closing += (sender, e) =>
    {
        if (HostCommands.ShutdownCommand.CanExecute(e))
            HostCommands.ShutdownCommand.Execute(e);
    };
}

And clients can register as follows, e.g

public SomeViewModel(IEventAggregator eventService)
{
    //blah, blah, blah...

    HostCommands.ShutdownCommand.
        RegisterCommand(new DelegateCommand<object>(_ => Save()));
}

Update

I do not handle the cancel scenario, but you could implement this via the object which is passed to the command. For instance in the above code I pass in a CancelEventArgs which clients could manipulate i.e. by setting Cancel=true. I could inspect this value in my Shell closed event handler after the command has execute to derive whether I should cancel closing the shell. This pattern can be expanded on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文