15

我有一个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 };
        }
    }
}

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);
            }
        }
    }
}

按下按钮时,红色边界应变为蓝色。显然渲染器没有注意到更改的属性。如何触发重绘?

(此示例适用于 iOS。但我的问题也适用于 Android。)

4

2 回答 2

10

首先,把你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); }
}

然后,在您的渲染器中:

protected override void OnElementPropertyChanged (object sender, PropertyChangedEventArgs e)
{
    base.OnElementPropertyChanged (sender, e);

    if (e.PropertyName == MyButton.BoundaryColorProperty.PropertyName)
        SetNeedsDisplay ();
}
于 2014-08-05T07:14:26.790 回答
9

需要进行两项修改:

  1. OnPropertyChanged在属性的设置器中调用BoundaryColor

    public class MyButton: Button
    {
        Color boundaryColor = Color.Red;
    
        public Color BoundaryColor {
            get {
                return boundaryColor;
            }
            set {
                boundaryColor = value;
                OnPropertyChanged();  // <-- here
            }
        }
    }
    
  2. 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)
        {
            // ...
        }
    }
    

注意:OnElementChanged订阅内部而不是构造函数 似乎很重要。否则 aSystem.Reflection.TargetInvocationException被提出。

于 2014-08-05T18:29:54.820 回答