Search code examples
xamarin.formsmvvmcross

Problem seen creating View-ViewModel lookup table - you have more than one View registered for the ViewModels


I started an Xamarin.Froms project with MvvmCross. I followed the documentation on the offical MvvmCross website to start the Android project with Xamarin.Forms. Here is my code in my Core project:

public class App : MvxApplication
{
    public App()
    {

    }

    public override void Initialize()
    {
        base.Initialize();

        Mvx.IoCProvider.RegisterSingleton(new NavigationStack());
        Mvx.IoCProvider.RegisterSingleton<IMvxAppStart>(new MvxAppStart<MainViewModel>(this, Mvx.IoCProvider.Resolve<IMvxNavigationService>()));
    }
}

public class MainViewModel : BaseViewModel
{
    public MainViewModel(NavigationStack navigationStack) : base(navigationStack)
    {
    }
}

Code that's in my Forms project: MainView.xaml:

<views:MvxContentPage x:TypeArguments="viewModels:MainViewModel"
xmlns="http://xamarin.com/schemas/2014/forms" 
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
xmlns:views="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms"
xmlns:viewModels="clr-namespace:MyApp.Core.ViewModels;assembly=MyApp.Core"
x:Class="MyApp.Forms.Views.MainView">

    <ContentPage.Content>
        <StackLayout Margin="10">
            <Label Text="Subtotal" />
        </StackLayout>
    </ContentPage.Content>

</views:MvxContentPage>

MainView.xaml.cs:

public partial class MainView : MvxContentPage<MainViewModel>
{
    public MainView()
    {
        InitializeComponent();
    }
}

In my Android project:

[Activity(
    Label = "MyApp.Droid",
    Theme = "@style/MyTheme",
    MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
    LaunchMode = LaunchMode.SingleTask)]
public class MainActivity : MvxFormsAppCompatActivity<MvxFormsAndroidSetup<Core.App, Forms.App>, Core.App, Forms.App>
{
    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(bundle);
    }
}

It compiles, but when I launch the app I get the exception:

MvvmCross.Exceptions.MvxException: Problem seen creating View-ViewModel lookup table - you have more than one View registered for the ViewModels: 2*MainViewModel (MainActivity,MainView)


Solution

  • If your ViewModel is called MainViewModel and your Forms page is too, you might get a name conflict because MvvmCross will have 2 view to viewmodel lookups. You can prevent this by naming your Activity differently like "FormsActivity.cs".

    You could also rename your MainViewModel to MvxMainViewModel(whatever you like), then this exception will disappear.