【发布时间】:2018-04-21 11:56:24
【问题描述】:
我有一张地图,显示点之间的路线。这是可行的,但现在 我想从 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:自定义地图)
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 事件。 所以我无法获得更改后的值。我只知道它确实发生了变化(使用 OnElementPropertyChanged)。
如果有人知道如何绕过这种现象...欢迎所有建议 ;-) 提前致谢!
【问题讨论】:
-
您可以使用 e.PropertyName 查找更改的属性
-
@G.Sharada 我知道该属性已更改。它是我想要的价值:-)
-
你通过
Element.RouteColor获取值——Element代表表单元素,而Control代表原生控件。 -
@G.Sharada 有趣!我确实有一个“元素”成员变量。但我没有可访问的“Element.RouteColor”...
-
@G.Sharada 它woooorrkkss !非常感谢 !!如果您将此添加为答案,我会选择它作为工作解决方案。
标签: android xamarin binding xamarin.forms