gpt4 book ai didi

c# - 如何在 WPF 中使用一次性 View 模型?

转载 作者:可可西里 更新时间:2023-11-01 08:22:59 26 4
gpt4 key购买 nike

如果 View 模型引用非托管资源或具有事件处理程序(例如在调度程序计时器上处理已过),我如何确保 View 模型被正确处理。在第一种情况下,终结器是一个选项,虽然不理想,但在后者中,它永远不会被调用。我们如何判断何时不再有 View 附加到 View 模型。

最佳答案

我通过执行以下操作实现了这一点:

  1. 从 App.xaml 中删除 StartupUri 属性。
  2. 按如下方式定义我的 App 类:

    public partial class App : Application
    {
    public App()
    {
    IDisposable disposableViewModel = null;

    //Create and show window while storing datacontext
    this.Startup += (sender, args) =>
    {
    MainWindow = new MainWindow();
    disposableViewModel = MainWindow.DataContext as IDisposable;

    MainWindow.Show();
    };

    //Dispose on unhandled exception
    this.DispatcherUnhandledException += (sender, args) =>
    {
    if (disposableViewModel != null) disposableViewModel.Dispose();
    };

    //Dispose on exit
    this.Exit += (sender, args) =>
    {
    if (disposableViewModel != null) disposableViewModel.Dispose();
    };
    }
    }

关于c# - 如何在 WPF 中使用一次性 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6983801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com