【问题标题】:ViewModel instances not disposed after navigation导航后未释放 ViewModel 实例
【发布时间】:2018-02-28 15:16:24
【问题描述】:

UWP 应用程序(Prism.Unity NuGetPackage 6.3.0)

当多次导航到同一个页面时,会创建其视图模型的新实例,而旧的实例会保存在内存中并且不会被释放。

这会导致崩溃,因为全局事件会使用事件聚合器多次触发,也会被监听它的旧 ViewModel 接收。

我们使用 NavigationService 来导航页面。我们的页面和用户控件在 XAML 中使用prismMvvm:ViewModelLocator.AutoWireViewModel="True" 绑定到视图模型。

我们已经看到一些关于类似问题的主题,解决方案是使用 Regions 添加区域行为。但是,据我所知,Prism UWP 在其当前版本中不支持区域。

我们认为问题与 ViewModelLocator 和 NavigationService 有关,因为使用 Container.RegisterType 和不同的 LifetimeManager 注册视图模型没有效果。

崩溃示例可以从 GitHub 下载:App1.zip

复制:

  1. 执行应用程序
  2. 在 Test1 和 Test2 之间多次导航
  3. 点击“RaiseEvent”以执行全局事件
  4. 记录其哈希码的所有实例
  5. 应用程序应该在某个时候崩溃

【问题讨论】:

    标签: c# uwp prism


    【解决方案1】:

    这会导致崩溃,因为全局事件会使用事件聚合器多次触发,也会被监听它的旧 ViewModel 接收。

    当您从一个页面导航到另一个页面时,您可以取消订阅该事件。

    例如:

    public class Test1PageViewModel : ShellIntegratedViewModel
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly INavigationService _navigationService;
        Action action;
        public Test1PageViewModel(IEventAggregator eventAggregator, INavigationService navigationService)
            : base(eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _navigationService = navigationService;
    
            NavigateCommand = new DelegateCommand(OnNavigateCommand);
            action = new Action(()=> {
                _eventAggregator.GetEvent<LogEvent>().Publish("Test1 Hashcode: " + this.GetHashCode());
            });
            _eventAggregator.GetEvent<TestEvent>().Subscribe(action);
        }
        private void OnNavigateCommand()
        {
            _eventAggregator.GetEvent<TestEvent>().Unsubscribe(action);
            _navigationService.Navigate("Test2", null);
        }
    
        public DelegateCommand NavigateCommand { get; private set; }
    }
    

    【讨论】:

    • 订阅不会让订阅者保持活跃,除非你告诉它。
    猜你喜欢
    • 2013-03-29
    • 1970-01-01
    • 2018-04-08
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多