WhenActivated is called twice when used in Views and ViewModels hosted in ViewModelViewHost control

前端 未结 2 1996
感动是毒
感动是毒 2021-02-09 03:53

My app uses views, which implement IViewFor interface. The views are registered with the dependency resolver in AppBootstrapper. The app displ

相关标签:
2条回答
  • 2021-02-09 04:07

    The WhenActivated call used in SubView returns an IDisposable object, which can be used within the same call to WhenActivated. This will remove your subscription from activation events upon deactivation. Doing so prevents the secondary activation and disposal from occurring.

    In the SubView constructor, change this:

    this.WhenActivated(d =>
    {
        Debug.WriteLine("SubView activated.");
        d(Disposable.Create(() => { Debug.WriteLine("SubView deactivated."); }));
    
        d(this // ViewModel -> DataContext
            .WhenAnyValue(v => v.ViewModel)
            .BindTo(this, v => v.DataContext));
    });
    

    to this:

    System.IDisposable whenActivatedSubscription = null;
    whenActivatedSubscription = this.WhenActivated(d =>
    {
        Debug.WriteLine("SubView activated.");
        d(Disposable.Create(() => { Debug.WriteLine("SubView deactivated."); }));
    
        d(this // ViewModel -> DataContext
            .WhenAnyValue(v => v.ViewModel)
            .BindTo(this, v => v.DataContext));
        d(whenActivatedSubscription); // <- Dispose of the activation subscription here
    });
    

    The reason why this solution works is because since your view is being destroyed, the activation itself needs to be disposed of as a part of this process as well.

    0 讨论(0)
  • 2021-02-09 04:17

    You can check this link. There is a very good explenation of everything. This is all I can offer without the knowledge of what you did in the "View" itself.

    It is possible that the "ViewModel and View" are called twice because you are creating two LoadingViewModels.

    0 讨论(0)
提交回复
热议问题