dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

MVVM Bindings for .NET iOS and .NET Android

Open cosminstirbu opened this issue 3 years ago • 0 comments

Overview

At the moment there is no library out there that allows you to create bindings between your ViewModels and your iOS / Android views (UIViewController / Fragments) with weak reference support.

MVVMLight was great in providing that via the SetBinding and SetCommand extensions.

I understand that .NET Community Toolkit is to be platform agnostic, however I believe it's worth starting the conversation here and then maybe finding a proper home for these new bindings.

Weak reference support is important because on .NET iOS (Xamarin.iOS) there is no proper lifecycle method where you can unbind. dealloc is not called due strong circular references and due to how Objective-C and .NET memory management works. ViewWillAppear / ViewWillDisappear are not proper candidates because hooking up the bindings every time the view will appear has a noticeable impact on performance.

That's why weak references are helpful because they avoid memory leaks and circular strong references between the ViewModel and the View. Also, there's no risk if we don't explicitly unbind, because the lifetime of the View matches the one of the ViewModel, meaning that once the screen is dismissed, the ViewModel won't ever update the View - which is what we want.

API breakdown

Mirror MVVMLight APIs with one additional enhancement:

  • Have SetCommand return an object (instead of void) to be able to detach the command. Detaching the command is useful in the use case where you display a list and the cells (views) are recycled (virtualised), this allows you to avoid a command being connected to the button of its previous recycled view.

Usage example

iOS - https://github.com/lbugnion/sample-crossplatform-flowers/blob/8aaee33425388c175f912e89a96df00ca8976645/Flowers.iOS/MainViewController.cs#L47

Android - https://github.com/lbugnion/sample-crossplatform-flowers/blob/8aaee33425388c175f912e89a96df00ca8976645/Flowers.Droid/MainActivity.cs#L41

Breaking change?

No

Alternatives

There might be alternatives such as MvvmCross or Prism - but based on my minimal research, they have a large footprint, as they force you to subclass from their base classes.

Ideally the API would mirror MVVMLight - which is exclusively based on extensions, and it doesn't force you to subclass any other classes.

Additional context

No response

Help us help you

No, just wanted to propose this

cosminstirbu avatar Aug 05 '22 11:08 cosminstirbu