Search code examples
xamarinxamarin.iosmvvmcross

MvvmCross iPhone and iPad best practices


I have a question regarding Xamarin.iOS and MvvmCross. What are the best practices to show a View for iPhone and iPad with the same ViewModel but different Views?

If i put the same ViewModel to the two Views I get the following exception:

MvvmCross.Platform.Exception.MvxException Problem seen creating View-ViewModel lookup table - you have more than one View registered for the same ViewModels

Is the best practice to create another ViewModel that derives from the first, and then from the View execute different logic dependently if the device is iPhone or iPad?


Solution

  • It is not possible to create two Views for one ViewModel. MvvmCross, just like other MVVM libraries, uses reflection to create a Dictionary of View and ViewModel relationships. This is a one-to-one operation. If you try to register several Views for a single ViewModel in your container, a MvxException will be thrown as you pointed out yourself.

    The simplest way to circumvent this behaviour, is to create a new ViewModel (and a new View) which simply derives from the first ViewModel.

    public class ViewModelA
    {
        public ViewModelA()
        { 
            // Constructor
        }
    
        // Properties, Methods, etc.
    
    }
    

    After creating ViewModelA, you can now create a new one, ViewModelB which derives from the former:

    public class ViewModelB : ViewModelA
    {
        public ViewModelA() : base() { }
    }