Fal*_*lko 12 android custom-renderer ios xamarin xamarin.forms
我有一个MyButton
带有为iOS实现的自定义渲染器的可视元素.
共享:
namespace RendererTest
{
public class MyButton: Button
{
public Color BoundaryColor { get; set; }
}
public static class App
{
public static Page GetMainPage()
{
var button = new MyButton { Text = "Click me!", BoundaryColor = Color.Red };
button.Clicked += (sender, e) => (sender as MyButton).BoundaryColor = Color.Blue;
return new ContentPage { Content = button };
}
}
}
Run Code Online (Sandbox Code Playgroud)
iOS版:
[assembly:ExportRenderer(typeof(MyButton), typeof(MyButtonRenderer))]
namespace RendererTest.iOS
{
public class MyButtonRenderer: ButtonRenderer
{
public override void Draw(RectangleF rect)
{
using (var context = UIGraphics.GetCurrentContext()) {
context.SetFillColor(Element.BackgroundColor.ToCGColor());
context.SetStrokeColor((Element as MyButton).BoundaryColor.ToCGColor());
context.SetLineWidth(10);
context.AddPath(CGPath.FromRect(Bounds));
context.DrawPath(CGPathDrawingMode.FillStroke);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
按下按钮时,红色边界应变为蓝色.显然渲染器没有注意到已更改的属性.如何触发重绘?
(此示例适用于iOS.但我的问题也适用于Android.)
首先,将您BoundaryColor
转变为可绑定的属性.这不是必需的,触发INPC
事件就足够了,但是你可以绑定它:
public static readonly BindableProperty BoundaryColorProperty =
BindableProperty.Create ("BoundaryColor", typeof(Color), typeof(MyButton), Color.Default);
public Color BoundaryColor {
get { return (Color)GetValue (BoudaryColorProperty); }
set { SetValue (BoundaryColorProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)
然后,在你的渲染器中:
protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged (sender, e);
if (e.PropertyName == MyButton.BoundaryColorProperty.PropertyName)
SetNeedsDisplay ();
}
Run Code Online (Sandbox Code Playgroud)
需要进行两项修改:
OnPropertyChanged
在酒店的设置者内打电话BoundaryColor
:
public class MyButton: Button
{
Color boundaryColor = Color.Red;
public Color BoundaryColor {
get {
return boundaryColor;
}
set {
boundaryColor = value;
OnPropertyChanged(); // <-- here
}
}
}
Run Code Online (Sandbox Code Playgroud)在以下OnElementChanged
方法中订阅活动MyButtonRenderer
:
public class MyButtonRenderer: ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
Element.PropertyChanged += (s_, e_) => SetNeedsDisplay(); // <-- here
}
public override void Draw(RectangleF rect)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)注意:
在内部订阅OnElementChanged
而不是构造函数似乎很重要.否则a System.Reflection.TargetInvocationException
被提出.
归档时间: |
|
查看次数: |
19112 次 |
最近记录: |