gpt4 book ai didi

c# - 将构造函数参数绑定(bind)到 Xamarin.Forms 的 GoogleMaps

转载 作者:行者123 更新时间:2023-12-03 10:15:34 24 4
gpt4 key购买 nike

我使用 MVVMCross 使用 GoogleMaps 开发简单的 Xamarin.Forms 应用程序。我的目标是在启动 map 时将 map 的位置置于用户当前位置。不幸的是,我不知道如何将这些值绑定(bind)到 GoogleMaps 的构造函数。现在它只是静态值,但我想从 CurrentLocation 对象(具有这些属性)传递纬度和经度值。

看法:

<ContentPage.Content>
<maps:Map MapType="Street" IsShowingUser="True" HasZoomEnabled="True">
<x:Arguments>
<maps:MapSpan>
<x:Arguments>
<maps:Position>
<x:Arguments>
<x:Double>56.368533</x:Double>
<x:Double>3.258646</x:Double>
</x:Arguments>
</maps:Position>
<x:Double>0.01</x:Double>
<x:Double>0.01</x:Double>
</x:Arguments>
</maps:MapSpan>
</x:Arguments>
</maps:Map>
</ContentPage.Content>

这是我的 ViewModel 的一部分:
public class NearbyBollardsMapViewModel : MvxViewModel
{
private Location _currentLocation;

public Location CurrentLocation
{
get => _currentLocation;
set
{
_currentLocation = value;
RaisePropertyChanged(() => CurrentLocation);
}
}

public NearbyBollardsMapViewModel(ILocationService locationService)
{
this._locationService = locationService;
CurrentLocation = _locationService.GetCurrentUsersLocation().Result;
}
}

最佳答案

您需要创建一个从 Maps 扩展的 PCL 类并向其添加 BindableProperty。
1º - 创建一个类并从 Xamarin.Forms.Maps.Map 扩展它
(我包含了 Bindable 属性的代码,你可以阅读更多 Here )

public class BindableMap : Xamarin.Forms.Maps.Map
{
public BindableMap()
{

}

public MapSpan MapSpan
{
get { return (MapSpan)GetValue(MapSpanProperty); }
set { SetValue(MapSpanProperty, value); }
}

public static readonly BindableProperty MapSpanProperty = BindableProperty.Create(
propertyName: "MapSpan",
returnType: typeof(MapSpan),
declaringType: typeof(BindableMap),
defaultValue: null,
defaultBindingMode: BindingMode.TwoWay,
validateValue: null,
propertyChanged: MapSpanPropertyChanged);

private static void MapSpanPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
try
{
var thisInstance = bindable as BindableMap;
var newMapSpan = newValue as MapSpan;

thisInstance?.MoveToRegion(newMapSpan);
}
catch (Exception ex)
{

}
}

}
2º - 添加将用于在 ViewModel 中绑定(bind) MapSpan 的属性
private MapSpan _mapSpanView;
public MapSpan MapSpanView
{
get { return _mapSpanView; }
set { SetProperty(ref _mapSpanView, value); }
}

...

Position position = new Position((double)Latitude, (double)Longitude);
MapSpanView = MapSpan.FromCenterAndRadius(
prospectPosition,
Distance.FromMeters(2500)
);
3º - 然后将其绑定(bind)到 xaml
xmlns:map="clr-namespace:YourNameSpace.Mobile.TheFolderWhereTheClassIs"

...

<StackLayout x:Name="mapHolder">
<map:BindableMap
x:Name="map"
MapSpan="{Binding MapSpanView}"
MapType="Street" IsShowingUser="True" HasZoomEnabled="True"/>
</StackLayout>

关于c# - 将构造函数参数绑定(bind)到 Xamarin.Forms 的 GoogleMaps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com