Interacting with the UI from the view model without breaking MVVM
Commands help you invoke a method in a view model when some action is executed in the UI. However, sometimes you may need to perform the opposite task: call a method in a UI control when some logic is executed in your view model. For example, let’s assume, you need to scroll CollectionView
down each time a user adds a new item to the bound collection in the view model. Let’s see how to accomplish this task using WeakReferenceMessenger, available in CommunityToolkit.Mvvm
.
Definition
WeakReferenceMessenger
enables communication between different parts of an application without creating strong references between objects. Weak references allow you to avoid memory leaks even if you don’t unregister a message handler.
Getting ready
Start with the project you got after executing the fourth recipe of this chapter: Initializing bound collections without freezing the UI. This project is available...