如何在 MAUI 中将变量传递给 GraphicsView

问题描述 投票:0回答:1

我想将变量传递到 GraphicView 中以通过按下按钮等方式更新绘图。

我在 Stack Overflow 上浏览了几个关于这个问题的例子。 (我试图发布链接,但后来我被告知我的问题似乎是垃圾邮件。) 但是,我无法让它发挥作用。有人可以告诉我我做错了什么吗?

XAML

<?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>

        <GraphicsView HeightRequest="400"
                      WidthRequest="400">
            <GraphicsView.Drawable>
                <drawable:GraphicsDrawable2 Test="{Binding testVariable}"/>
            </GraphicsView.Drawable>
        </GraphicsView>
        
    </VerticalStackLayout>
</ContentPage>

CS 文件

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));
    public int Test
    {
        get => (int)GetValue(TestProperty);
        set => SetValue(TestProperty, value);
    }


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

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;
    }
}
c# graphics maui drawable maui-community-toolkit
1个回答
0
投票

尝试引用页面名称的绑定;它应该有效。问题是您的元素不知道在哪里可以找到“test”属性。通过引用页面名称,它将在“NewPage1”类中搜索并找到它。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:drawable="clr-namespace:MauiApp1"             
         x:Class="MauiApp1.NewPage1"      
         x:Name="PageName"
         Title="NewPage1">
<VerticalStackLayout>
    <GraphicsView HeightRequest="400"
                  WidthRequest="400">
        <GraphicsView.Drawable>
            <drawable:GraphicsDrawable2 Test="{Binding testVariable,Source={x:Reference PageName}}"/>
        </GraphicsView.Drawable>
    </GraphicsView>

</VerticalStackLayout>

请注意,我添加了页面名称并使用它在属性绑定中引用。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.