Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the view model instance in a XAML page's code behind (Xamarin Forms) in Prism

Below is the definition of my page in Xamarin Forms with Prism MVVM framework:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps"
             x:Class="MyProject.UI.Modules.Views.MapPage">

.....
</ContentPage>

Unfortunately Xamarin maps are not MVVM-ready when it comes to binding pins, etc. Therefore, I need to make some code changes in the C# code behind of the page. How can I access the instance of the ViewModel interacting with this page in the code behind?

like image 845
Arash Avatar asked Jan 31 '17 03:01

Arash


People also ask

What is a view in XAML?

View: For WPF applications view is the XAML based user interface. It contains different user controls to present the information. It controls values that are bound to the model's properties. Control's value can be bound in multiple modes. ViewModel: ViewModel is the middle layer between the view and model.

How do I add a XAML page in Xamarin?

Xamarin Forms is updated in Android project. For Adding Xaml ContentPage, right click XamFormConPage(Portable) project and select ADD-> NewItem. Select -> CrossPlatform -> FormXamlPage -> Give it a relevant name. Now, XAML Content Page is added to your project.

What is XAML in Xamarin forms?

In a Xamarin. Forms application, XAML is mostly used to define the visual contents of a page and works together with a C# code-behind file. The code-behind file provides code support for the markup. Together, these two files contribute to a new class definition that includes child views and property initialization.


1 Answers

You could always monitor for property changes on the ViewModel and use the values to update the map. To get a hold of the ViewModel, just cast your BindingContext

Example : ((MainPageViewModel)this.BindingContext)

Example link : https://github.com/PrismLibrary/Prism-Samples-Forms/blob/7b0ce9ca31f07dea5020dbd5875d16f18bcdf09a/ContosoCookbook/ContosoCookbook/ContosoCookbook/Views/MainPage.xaml.cs#L16

like image 190
Depechie Avatar answered Sep 28 '22 02:09

Depechie