Saturday, 25 September 2010

MonoTouch meet WindowsPhone7

This is a very basic example of how you can share data and code between the iPhone platform (using MonoTouch) and recently RTM'd Windows Phone 7.

The code is available on github... notice that the source data (restaurants.xml file) and class file (Objects.cs) are identical on both platforms, as is the XmlSerialization code that parses the data into memory for display.

You will see there is a lot more 'user code' in the MonoTouch project for iPhone - this is due to the laborious way that UITableViews must be coded*; whereas the WP7's Silverlight heritage allows some very neat databinding scenarios.

I think it depends on your definition of MVVM... if you are talking about the Microsoft flavor that relies heavily on the implicit databinding available in XAML (such that you can set the DataContext of a screen to your ViewModel, and things "just work") then that will be hard to replicate on the iOS and Android platforms which lack that capability.

However, at a more general level, I think you can certainly aim to share your model across all three platforms... but how you bind them to the UI will certainly have to adapt.

The short answer is: I don't think you can write cross-platform ViewModels.

In WP/XAML, you'll probably want to convert collections from the shared code into something Observable (and persist changes back). But otherwise your ViewModel can expose Model properties and expect the databinding to display/set the data - saving you lots of code.

On the other platforms, your binding to the UI will need to do more work to present and persist data on the native UI controls for that platform. Lots of left-to-right assignments will be needed to marshal data from objects to UI and back again.

If your ViewModels are also housing validation or other logic, you can certainly move that up into the shared code - this is what I'd call the Business Logic - then consume those functions in your ViewModel (on WP) or other UI binding.

Hope that makes some sense? What specifically are you concerned about?

There is a more sophisticated example - http://mwc.xamarin.com/ (https://github.com/xamarin/mobile-samples/tree/master/MWC) - that you might find useful. You might like to also read about http://www.MonoCross.net which is a cross-platform *MVC* framework - it's open source so you might get some ideas from that too.