通过BindableProperty传递ObservableProperty至GraphicsView画布失败排查
问题分析与解决方案
错误原因
- IDrawable不支持绑定
IDrawable接口未继承BindableObject,而BindableProperty只能在继承BindableObject的类中生效,导致你的NewDrawable无法接收绑定值。 - 属性未关联BindableProperty
你定义的Vectors是普通自动属性,没有和VectorsProperty关联,绑定系统无法将ViewModel的值传递到该属性中。
修正后的Drawable代码
public class NewDrawable : BindableObject, IDrawable { // 定义BindableProperty,添加属性变化回调 public static readonly BindableProperty VectorsProperty = BindableProperty.Create( nameof(Vectors), typeof(float), typeof(NewDrawable), defaultValue: 0f, propertyChanged: OnVectorsChanged); // 关联BindableProperty的属性 public float Vectors { get => (float)GetValue(VectorsProperty); set => SetValue(VectorsProperty, value); } // 属性变化时触发重绘,确保画布更新 private static void OnVectorsChanged(BindableObject bindable, object oldValue, object newValue) { if (bindable is NewDrawable drawable && Application.Current?.MainPage?.FindByName<GraphicsView>("newDrawableView") is GraphicsView view) { view.Invalidate(); } } public void Draw(ICanvas canvas, RectF dirtyRect) { canvas.StrokeColor = Color.FromRgba("ebc500"); canvas.StrokeSize = 15; canvas.StrokeLineCap = LineCap.Round; canvas.DrawArc(40, 40, 200, 200, 90, Vectors, true, false); } }
额外注意事项
- 确保页面的
BindingContext已正确设置为ViewModel实例,例如在页面构造函数中:public YourPage() { InitializeComponent(); BindingContext = new YourViewModel(); } - 你ViewModel中使用
[ObservableProperty]的代码是正确的,它会自动触发PropertyChanged事件,保证值变化时能通知绑定系统。
内容的提问来源于stack exchange,提问作者Jonas Sønderby
相关产品推荐
相关产品推荐

