我有一张显示点之间路线的地图。这是有效但现在我想从PCL传递一些颜色值。我有一个用于android的自定义渲染器和一个充当PCL和android之间的桥梁的类,其中包含可绑定属性。 (对于地图,我使用PCL实现并使用自定义渲染器对其进行扩展)
现在我得到了:
(android:CustomMapRenderer)
[assembly: ExportRenderer(typeof(CustomMap), typeof(MapOverlay.Droid.CustomMapRenderer))]
namespace MapOverlay.Droid
{
public class CustomMapRenderer : MapRenderer , ICustomMap
{
List<Position> routeCoordinates;
Int32 RouteColor;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
// Unsubscribe
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
routeCoordinates = formsMap.RouteCoordinates;
Control.GetMapAsync(this);
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
if (e.PropertyName == "VisibleRegion")
{
var polylineOptions = new PolylineOptions();
polylineOptions.InvokeColor(0x66FF0000);
foreach (var position in routeCoordinates)
{
polylineOptions.Add(new LatLng(position.Latitude, position.Longitude));
}
NativeMap.AddPolyline(polylineOptions);
}
}
public void working()
{
Log.Debug("xxxx", "WORKING");
}
}
}
现在这个班级充当从PCL到Android的桥梁 (PCL:CustomMap)
namespace SomeNamespace
{
public class CustomMap : Map
{
public static readonly BindableProperty RouteCoordinatesProperty =
BindableProperty.Create<CustomMap, List<Position>>(p => p.RouteCoordinates, new List<Position>());
public static readonly BindableProperty RouteColorProperty =
BindableProperty.Create<CustomMap, int>(p => p.RouteColor, 0x66FF0000);
//Property used to add points to the map. Then polyline utility will draw a line beteween thoses points
public List<Position> RouteCoordinates
{
get { return (List<Position>)base.GetValue(RouteCoordinatesProperty); }
set {
base.SetValue(RouteCoordinatesProperty, value);
}
}
public Int32 RouteColor
{
get { return (Int32)base.GetValue(RouteColorProperty); }
set { base.SetValue(RouteColorProperty, value); }
}
public CustomMap()
{
RouteCoordinates = new List<Position>();
}
}
}
因为你可以看到我添加了一个Int32 RouteColor
变量,它应该在CustomMapRenderer中用来改变显示路径的颜色。
但是当我在我的PCL代码中更改此值时:
mCustomMap.RouteColor = 0x22AA0000;
它会触发OnElementPropertyChanged响应,但不会触发OnElementChanged事件。 所以我无法获得改变的价值。我只知道DID已更改(使用OnElementPropertyChanged)。
如果有人知道如何绕过这种现象......欢迎所有建议;-) 提前谢谢!
答案 0 :(得分:0)
Element
表示表单元素,在本例中应为CustomMap
。您可以使用它来检索属性值。
例如:
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
....
//if RouteColor is the property that changed
if (e.PropertyName == nameof(CustomMap.RouteColor))
{
//get new value
var newColor = (Element as CustomMap)?.RouteColor;
//and, update native control
....