Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for Xamarin.Mac MVVM pattern

I'm developing a WPF desktop application that I'd also like to run on Mac via Xamarin.Mac. I've taken great care to separate as much core code as possible into a PCL, and keep the WPF-specific code as thin as possible.

The UI architecture is MVVM. All of my viewmodels, implementing INotifyPropertyChanged, in are in my core PCL. The WPF UI components can then directly bind to those viewmodel properties.

My question is: how can I use my "portable" PCL viewmodels from the Xamarin.Mac side so that I can use Cocoa databinding?

The main problem appears to be that, in order to interact with Cocoa databindings, the viewmodels must inherit from NSObject, use the Register annotation to expose the properties, and use the WillChangeValue/DidChangeValue methods for notifying observers. I don't see a way to do this for the viewmodels inside the PCL, mainly because I can't have them inherit from NSObject if those same classes are to remain usable from the WPF side.

I'd like to avoid using frameworks such as MVVMCross or MVVMLight because they contain a lot of things that I don't need. However, if there's no other way I'm open to using them.

like image 267
tdenniston Avatar asked Jan 17 '26 19:01

tdenniston


1 Answers

The irony.... I'm at the same crossroads you've mentioned almost a year later. I was able to accomplish this without using MVVMLight or MVVMCross.

In my ViewModelBase, I used the SetProperty API to inspect first to see if the value is different from it's previous value. If it is different, I use the MACOS complier definition to invoke WillChangeValue/DidChangeValue accordingly, followed by the RaisePropertyChanged for all other platforms. Obviously I used the MACOS compiler def to subclass NSObject.

I came upon this stackoverflow post looking for a way to bind the ICommand interface to a Xamarin.Mac button. Apparently it's harder than I thought.

I suppose I could peek at the MVVMCross repository to see how they've accomplished this task. Anyway, I'm sure by now you've solved your multi-pcl-MVVM dilemma. Do share if you've done anything different than my approach.

like image 160
gcadmes Avatar answered Jan 19 '26 20:01

gcadmes