shady shady - 23 days ago 12
C# Question

Share a single ViewModel instance between pages in Xamarin Forms

When I declare my MainViewModel class in App.xaml, I get this error on load:

Xamarin.Forms.Xaml.XamlParseException: Position 7:6. Cannot assign property "Resources": type mismatch between "MyPCL.Client.ViewModels.MainViewModel" and "Xamarin.Forms.ResourceDictionary"

<Application.Resources>
<viewModels:MainViewModel x:Key="MainViewModel"/>
</Application.Resources>


How can I declare on global ViewModel so on every page I can do this:

BindingContext="{StaticResource MainViewModel}"

Answer

It's because you need te declare a ResourceDictionary inside the Application.Reousrces tag:

  <Application.Resources>
    <ResourceDictionary>
        <viewModels:MainViewModel x:Key="MainViewModel"/>
    </ResourceDictionary>
  </Application.Resources>