Xamarin.Forms力重绘查看自定义渲染器 [英] Force redraw of Xamarin.Forms View with custom renderer
问题描述
我有一个视觉元素用作MyButton
与iOS版实现了自定义渲染
I have a visual element MyButton
with a custom renderer implemented for 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的:
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);
}
}
}
}
当按下按钮,红色的边界应该变成蓝色。显然,渲染器不注意到更改的属性。我怎样才能触发重绘?
When pressing the button, the red boundary should become blue. Apparently the renderer does not notice the changed property. How can I trigger a redraw?
(这个例子是适用于iOS。但我的问题适用于Android作为好。)
(This example is for iOS. But my question applies to Android as well.)
推荐答案
被要求两个修改:
-
呼叫
OnPropertyChanged
在BoundaryColor
setter方法内:
Call
OnPropertyChanged
within the setter of theBoundaryColor
property:
public class MyButton: Button
{
Color boundaryColor = Color.Red;
public Color BoundaryColor {
get {
return boundaryColor;
}
set {
boundaryColor = value;
OnPropertyChanged(); // <-- here
}
}
}
订阅中事件的 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
,而不是在构造函数中订阅。否则, System.Reflection.TargetInvocationException
升高。
Note:
It seems to be important to subscribe within OnElementChanged
and not the constructor. Otherwise a System.Reflection.TargetInvocationException
is raised.
这篇关于Xamarin.Forms力重绘查看自定义渲染器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!