如何在 Prism 的 XAML 页面代码隐藏 (Xamarin Forms) 中访问视图模型实例

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

以下是我在 Xamarin Forms 中使用 Prism MVVM 框架定义的页面:

<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>

不幸的是,在绑定引脚等方面,Xamarin 映射不是 MVVM 就绪的。因此,我需要在页面后面的 C# 代码中进行一些代码更改。如何在后台代码中访问与此页面交互的 ViewModel 实例?

您始终可以监视 ViewModel 上的 属性 更改,并使用这些值来更新地图。 要获取 ViewModel,只需投射 BindingContext

示例:((MainPageViewModel)this.BindingContext)

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