如何在MAUI中向GraphicsView传递变量以更新绘图
问题分析与解决
你的代码核心问题是:当Test属性值变化时,GraphicsDrawable2没有触发GraphicsView的重绘操作。IDrawable的Draw方法默认只会在控件初始化、布局变更时执行,属性变更不会自动触发重绘。另外,当前代码缺少触发变量更新的交互控件(比如按钮)。
修复步骤
1. 修改GraphicsDrawable2,添加属性变化回调触发重绘
给TestProperty添加propertyChanged回调,在属性值变化时通知关联的GraphicsView重新绘制:
using System.Numerics; using Microsoft.Maui.Graphics; using Microsoft.Maui.Controls; namespace SleepDiary; public class GraphicsDrawable2 : BindableObject, IDrawable { public static BindableProperty TestProperty = BindableProperty.Create( nameof(Test), typeof(int), typeof(GraphicsDrawable2), propertyChanged: OnTestPropertyChanged); // 添加属性变化回调 public int Test { get => (int)GetValue(TestProperty); set => SetValue(TestProperty, value); } private static void OnTestPropertyChanged(BindableObject bindable, object oldValue, object newValue) { // 获取当前Drawable实例 var drawable = bindable as GraphicsDrawable2; // 找到关联的GraphicsView并触发重绘 if (drawable != null && drawable.Parent is GraphicsView graphicsView) { graphicsView.Invalidate(); // 通知GraphicsView重新绘制 } } public void Draw(ICanvas canvas, RectF dirtyRect) { canvas.StrokeColor = Colors.Black; canvas.StrokeSize = 1; canvas.DrawLine(0, 0, Test, Test); canvas.DrawLine(100, 0, 100, 100); } }
2. 在XAML中添加触发变量更新的按钮
给VerticalStackLayout添加按钮,绑定点击事件来修改testVariable:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SleepDiary.NewPage1" xmlns:drawable="clr-namespace:SleepDiary" Title="NewPage1"> <VerticalStackLayout Padding="20" Spacing="20"> <GraphicsView HeightRequest="400" WidthRequest="400"> <GraphicsView.Drawable> <drawable:GraphicsDrawable2 Test="{Binding testVariable}"/> </GraphicsView.Drawable> </GraphicsView> <!-- 添加按钮,点击时更新变量 --> <Button Text="增加线条长度" Clicked="OnIncreaseButtonClicked"/> <Button Text="减少线条长度" Clicked="OnDecreaseButtonClicked"/> </VerticalStackLayout> </ContentPage>
3. 在页面代码中实现按钮点击事件
修改NewPage1的代码,添加按钮点击逻辑来更新testVariable:
using Microsoft.Maui.Controls; namespace SleepDiary; public partial class NewPage1 : ContentPage { private int _testVariable; public int testVariable { get => _testVariable; set { if (_testVariable == value) return; _testVariable = value; OnPropertyChanged(); } } public NewPage1() { InitializeComponent(); BindingContext = this; testVariable = 100; } // 增加线条长度的点击事件 private void OnIncreaseButtonClicked(object sender, EventArgs e) { testVariable += 50; } // 减少线条长度的点击事件 private void OnDecreaseButtonClicked(object sender, EventArgs e) { testVariable = Math.Max(0, testVariable - 50); // 防止负数 } }
修复原理
- 当点击按钮修改
testVariable时,OnPropertyChanged会触发绑定更新,将新值传递给GraphicsDrawable2的Test属性。 TestProperty的变化回调会调用GraphicsView.Invalidate(),强制触发Draw方法重新执行,从而更新绘图内容。
内容的提问来源于stack exchange,提问作者Niklas Karlsson
相关产品推荐
相关产品推荐

