MAUI 如何在 ViewModel 中访问 XAML 地图 VisibleRegion

问题描述 投票:0回答:1

我在 XAML 中有一个 MAUI 地图控件,我需要访问 ViewModel 中的 VisibleRegion 属性,但该属性不可绑定。谁能帮我想出一个解决方法,如何在 ViewModel 中访问此信息?

这是XAML


<maps:Map x:Name="mapStoresNearby"
    MapType="Street"
    IsVisible="{Binding IsNotBusy}"
    ItemsSource="{Binding MapPins}">
    <maps:Map.ItemTemplate>
    <DataTemplate x:DataType="models:MapPin">
        <maps:Pin Location="{Binding Location}"
        Address="{Binding Address}"
        Label="{Binding Label}" 
        Type="{Binding Type}" />
        </DataTemplate>
    </maps:Map.ItemTemplate>
</maps:Map>

我需要访问视图模型中的这些属性,但不知道如何将信息从视图发送到视图模型。

    mapStoresNearby.VisibleRegion.Center.Latitude;
    mapStoresNearby.VisibleRegion.Center.Longitude;
    mapStoresNearby.VisibleRegion.Radius.Miles;

我可以在后面的代码中访问VisibleRegion,是否有正确的方法将它们传递给ViewModel?

mvvm data-binding maui
1个回答
0
投票

是的

VisibleRegion
是不可绑定的,我们不能直接在ViewModel中绑定它。但由于您可以在后面的代码中获取它,因此可以将其传递给 ViewModel。

我们可以使用

PropertyChanged
事件处理程序来检测
VisibleRegion
属性更改。

public MainPage()
{
    InitializeComponent();
    mapStoresNearby.PropertyChanged += Map_PropertyChanged;
    this.BindingContext = new MainPageViewModel();
}


private void Map_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if(e.PropertyName == nameof(Map.VisibleRegion))
    {
        //Suppose there is a Property called MyVisibleRegion which stores the VisibleRegion value
        (BindingContext as MainPageViewModel).MyVisibleRegion = mapStoresNearby.VisibleRegion;

    }
}

从上面的代码来看,每次

VisibleRegion
属性改变时,
Map_PropertyChanged
都会被调用。因此我们可以将
VisibleRegion
属性值传递给 ViewModel。

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.