Force redraw of Xamarin.Forms View with custom renderer

霸气de小男生 提交于 2019-12-03 11:19:06

First, turn you BoundaryColor into a bindable property. That's not required, firing INPC event is enough, but then you can bind to it:

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

then, in your renderer:

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

    if (e.PropertyName == MyButton.BoundaryColorProperty.PropertyName)
        SetNeedsDisplay ();
}

Two modifications were required:

  1. Call OnPropertyChanged within the setter of the BoundaryColor property:

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

Note: It seems to be important to subscribe within OnElementChanged and not the constructor. Otherwise a System.Reflection.TargetInvocationException is raised.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!