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

前端 未结 2 1994
感动是毒
感动是毒 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.

提交回复
热议问题