[英]ViewModel instances not disposed after navigation
UWP應用程序(Prism.Unity NuGetPackage 6.3.0)
多次導航到同一頁面時,將創建其視圖模型的新實例,而舊的則保留在內存中,並且不會被丟棄。
這會導致崩潰,因為使用事件聚合器多次觸發了全局事件,而舊的ViewModel也會使用事件聚合器來接收該事件聚合器。
我們正在使用NavigationService來瀏覽頁面。 我們的頁面和用戶控件通過XAML中的prismMvvm:ViewModelLocator.AutoWireViewModel="True"
綁定到視圖prismMvvm:ViewModelLocator.AutoWireViewModel="True"
。
我們已經看到了一些有關類似問題的線索,解決方案是使用Regions添加區域行為。 但是,據我所知,Prism UWP在當前版本中不支持區域。
我們認為問題與ViewModelLocator和NavigationService有關,因為使用Container.RegisterType和其他LifetimeManager注冊視圖模型無效。
可以從GitHub下載崩潰的示例: App1.zip
攝制:
這會導致崩潰,因為使用事件聚合器多次觸發了全局事件,而舊的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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.