2017-07-30 47 views
0

我正在加载我的针脚async,如果我不使用自定义地图,它会很好地工作。但是,如果我在我的Android project中使用自定义地图,则不再有效。我的custom Pin list为空。我可以理解这是因为我正在加载异步引脚,并且自定义引脚列表尚未初始化。但我该如何解决它?在所有平台(Android,iOS,UWP)中解决这个问题有多大功效?Xamarin.Forms在Android项目中加载引脚异步

public CustomMap Map { get; set; } 

    public async Task InitilizePins() 
    { 
     var pins = (await new SamplePins().GetPinsAsync()).ToList(); 
     Map.CustomPins = pins; 

     foreach (var customPin in pins) 
     { 
      Map.Pins.Add(customPin.Pin); 
     } 
    } 

    public class CustomMap : Map 
    { 
     public List<CustomPin> CustomPins { get; set; } 
    } 

这是我在Android中的自定义地图。我的自定义引脚在我的表单地图变量上为空。

 List<CustomPin> customPins; 

    protected override void OnElementChanged(ElementChangedEventArgs<Map> e) 
    { 
     base.OnElementChanged(e); 

     if (e.OldElement != null) 
     { 
      NativeMap.InfoWindowClick -= OnInfoWindowClick; 
     } 

     if (e.NewElement != null) 
     { 
      var formsMap = (CustomMap)e.NewElement; 

      customPins = formsMap.CustomPins; 
      ((MapView)Control).GetMapAsync(this); 
     } 
    } 
+0

为了确定我们需要完整的示例项目来跟踪此项目。但很可能你的渲染器在你设置你的引脚之前被调用。 –

回答

2

我可以理解,那是因为我加载销异步和自定义引脚列表尚未初始化。但我该如何解决它?

来解决这个问题的最快方法是从List<CustomPin>改变CustomPinsObservableCollection<CustomPin>(你需要改变你的项目相关的所有代码)。

然后在你的Android项目注册ObservableCollection<CustomPin>CollectionChanged事件:

protected override void OnElementChanged (Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e) 
{ 
    base.OnElementChanged (e); 

    if (e.OldElement != null) { 
     NativeMap.InfoWindowClick -= OnInfoWindowClick; 

    } 

    if (e.NewElement != null) { 
     var formsMap = (CustomMap)e.NewElement; 
     //register the CollectionChanged event 
     formsMap.CustomPins.CollectionChanged += CustomPins_CollectionChanged; 
     customPins = formsMap.CustomPins; 
     Control.GetMapAsync(this); 
    } 
} 

private void CustomPins_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
{ 
    customPins = (ObservableCollection<CustomPin>)sender; 
    //rerender all the pins in the map 
    NativeMap.Clear(); 

    foreach (var pin in customPins) 
    { 
     var marker = new MarkerOptions(); 
     marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude)); 
     marker.SetTitle(pin.Pin.Label); 
     marker.SetSnippet(pin.Pin.Address); 
      marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin)); 

     NativeMap.AddMarker(marker); 
    } 
    isDrawn = true; 
} 

然后,一旦你添加新的引脚,CustomPins_CollectionChanged将被触发,地图的引脚将被重新描绘。

+0

它实际上已将我的自定义引脚列表更改为ObservableCollection。我没有将我的customPins作为私人字段,而是将我的表格映射到它。如果我需要获取自定义引脚,我会从我的FormsMap字段中获取它。 – thatsIT

+0

顺便说一句,如果我需要做一些事情时,他们被添加,然后CollectionChanged修复。 (我只需要从我点击的集合中获取自定义引脚)。 – thatsIT