Добавить несколько пинов в Xamarin.Maps в MVVM - PullRequest
0 голосов
/ 04 февраля 2019

У меня возникают проблемы при попытке понять, как добавить булавки на карту в шаблоне MVVM.(У меня может быть несколько карт в представлении).

Вот мой код ViewModel.

<flv:FlowListView SeparatorVisibility="Default" HasUnevenRows="True" FlowItemTappedCommand="{Binding ItemTappedCommand}" FlowLastTappedItem="{Binding LastTappedItem}" FlowColumnMinWidth="600" FlowItemsSource="{Binding DashboardWidgets}" >
    <flv:FlowListView.FlowColumnTemplate>
                <StackLayout BackgroundColor="White" Margin="1">
                    <!--Map Widgets -->
                    <StackLayout BackgroundColor="{Binding bgcolor}" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" IsVisible="False" >
                        <StackLayout.Triggers>
                            <DataTrigger TargetType="StackLayout" Binding="{Binding resultsettype}" Value="map">
                                <Setter Property="IsVisible" Value="True"/>
                            </DataTrigger>
                        </StackLayout.Triggers>
                        <StackLayout Orientation="Vertical"  Padding="4" HeightRequest="400" WidthRequest="600">
                            <maps:Map x:Name="MyMap" IsShowingUser="true" MapType="Hybrid" />
                        </StackLayout>
                    </StackLayout>
                    <!--Image Widgets -->
                    <StackLayout BackgroundColor="{Binding bgcolor}" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" HeightRequest="200" WidthRequest="600" Padding="4" IsVisible="False">
                        <StackLayout.Triggers>
                            <DataTrigger TargetType="StackLayout" Binding="{Binding resultsettype}" Value="image">
                                <Setter Property="IsVisible" Value="True"/>
                            </DataTrigger>
                        </StackLayout.Triggers>
                        <StackLayout Padding="1" HeightRequest="200" WidthRequest="600">
                            <Image Source="{Binding contentvalue, Converter={StaticResource LocalBase64ToImageConverter}}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
                        </StackLayout>
                    </StackLayout>
    </flv:FlowListView.FlowColumnTemplate>

У меня есть наблюдаемая коллекция DashboardWidgets, которая может содержать карту,изображение, целое число или список.Если это карта, я получу все контакты в ВМ и каким-то образом привяжу их к карте.Поскольку я использую шаблон mvvm, я не должен получать доступ к карте в моей виртуальной машине, и, кроме того, я не имею ни малейшего понятия, как это сделать.

Так что я до сих пор пытался расширить карту, чтобы сделать контакты привязываемыми, но безуспешно.

public class ExtendedMap : Map
    {
     public static readonly BindableProperty PinsProperty = BindableProperty.Create(nameof(MultiPins), typeof(IList<Pin>), typeof(ExtendedMap), new List<Pin>());
     public List<Pin> MultiPins
         {
            get {
                        var val = (List<Pin>)GetValue(PinsProperty);
                        return new List<Pin>();
                         }
                    set => SetValue(PinsProperty, value);
                    }                
                }      
        }

Я попытался создать представление содержимого, связывающее его содержимое со свойством внутри vm, но безуспешно.

XAML: пробовал оба.Ни один не работал.

<contentview content={binding widgetResult } />
<contentview content={binding mapresult} />

VM: VM реализует IPropertyChanged.

var map = new Map(MapSpan.FromCenterAndRadius(new Position(37, -122), Distance.FromMiles(0.3)))
                {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand
                };
        (await GetMapPins(widget.filter)).ForEach(f => map.Pins.Add(f));
        widget.widgetResult = new ContentView
                {
                    Content = map
                 };
        widget.mapresult = map;

1 Ответ

0 голосов
/ 05 февраля 2019

Это ошибка:

public static readonly BindableProperty PinsProperty = BindableProperty.Create(nameof(MultiPins), typeof(IList<Pin>), typeof(ExtendedMap), new List<Pin>());

public List<Pin> MultiPins {...}

Имя BindableProperty ДОЛЖНО быть именем самого свойства, в данном случае «MultiPins», плюс «Свойство», поэтому имя BindableProperty ДОЛЖНО быть »MultiPinsProperty ", например:

public static readonly BindableProperty MultiPinsProperty = BindableProperty.Create(nameof(MultiPins), typeof(IList<Pin>), typeof(ExtendedMap), new List<Pin>());

public List<Pin> MultiPins {...}

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties#creating-a-property

Соглашение о присвоении имен для привязываемых свойств заключается в том, что идентификатор привязываемого свойства должен соответствовать имени свойства, указанному в методе Create, с«Собственность» добавлена ​​к нему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...