Skip to content

[BUG] WPF - ViewModelViewHost creates the old view again when switching to a new view model #2258

@TolikPylypchuk

Description

@TolikPylypchuk

Describe the bug
When a view model is changed for a ViewModelViewHost, it creates the old view again and only after that creates a new view, which can cause brief flickering of views. This happens in a WPF app on .NET Core 3.0 (not sure about other frameworks). ReactiveUI version is 10.5.31.

Steps To Reproduce
I've created a simple repo to reproduce the issue.

The view flickering is not actually visible there, but if you debug the app in Visual Studio, you'll see the log output. When switching the view from View1 to View2, the following log can be seen:

MainViewModel: Switching the view.
View1: Creating the view 1
View2: Creating the view 2

Expected behavior
The old view is not created again when switching to a new view.

Environment

  • OS: Windows 10 Home 1909

Additional context

The source of error is probably in the constructor of the ViewModelViewHost class:

var contractChanged = _updateViewModel.Select(_ => ViewContractObservable).Switch();
var viewModelChanged = _updateViewModel.Select(_ => ViewModel);

var vmAndContract = contractChanged.CombineLatest(viewModelChanged, (contract, vm) => new { ViewModel = vm, Contract = contract });

vmAndContract.Subscribe(x => ResolveViewForViewModel(x.ViewModel, x.Contract));

I've debugged this code, and x => ResolveViewForViewModel(x.ViewModel, x.Contract) is hit twice when switching the view model - first time with the old view model (hence creating the old view) and the second time with the new view model. I think this is becuase when a view model is changed, the contractChanged is fired, and then the viewModelChanged is fired, which is why vmAndContract is fired twice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions