我在理解.NET Maui中绑定的工作原理时遇到了问题.我的目标是有两种方式在CollectionView中显示比分,一种是带有数字的标签,另一种是图形表示.将分数绑定到标签上工作得很好,但绑定到抽屉上就不行了.如果我写一个数字而不是使用绑定,它会被很好地传递.

我做错了什么?

ProceduresPage.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"
             xmlns:model="clr-namespace:MediSkillApp.Model"
             xmlns:drawables="clr-namespace:MediSkillApp.Drawables"
             xmlns:viewmodel="clr-namespace:MediSkillApp.ViewModel"
             x:Class="MediSkillApp.View.ProceduresPage"
             x:DataType="viewmodel:ProceduresViewModel"
             Title="Alle mine indgreb">

    <Grid ColumnDefinitions="*"
          ColumnSpacing="5"
          RowSpacing="0">

        <CollectionView
            BackgroundColor="Transparent"
            ItemsSource="{Binding Procedures}"
            RemainingItemsThresholdReachedCommand="{Binding GetProceduresCommand}"
            RemainingItemsThreshold="5">
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="model:Procedure">
                    <VerticalStackLayout>
                        <Frame Margin="5">
                            <Grid ColumnDefinitions="64,*, 64">
                                <Image 
                                    Grid.Column="0"
                                    Source="{Binding Icon}"
                                    HeightRequest="48"
                                    WidthRequest="48"
                                    HorizontalOptions="Start"/>
                                
                                <VerticalStackLayout
                                    Grid.Column="1">
                                    <Label Text="{Binding ProcedureTypeString}"
                                           Style="{StaticResource Heading}"/>
                                    <Label Text="{Binding OpRoleString}"
                                           Style="{StaticResource NormalLabel}"/>
                                    <Label Text="{Binding Date, StringFormat='{0:dd/MM-yyyy}'}"
                                           Style="{StaticResource NormalLabel}"/>
                                </VerticalStackLayout>
                                
                                <VerticalStackLayout
                                    Grid.Column="2"
                                    IsVisible="{Binding IsScored}">

                                    <!-- this binding works -->
                                    <Label Text="{Binding AvgScore, StringFormat='{0:F2}'}" 
                                           HorizontalOptions="Center"/>

                                    <Image Source="scoremeter.png"/>
                                    
                                    <GraphicsView>
                                        <GraphicsView.Drawable>

                                            <!-- this binding does not -->
                                            <drawables:ScoreGaugeDrawable
                                                    Score="{Binding AvgScore}"/>
                                        </GraphicsView.Drawable>
                                    </GraphicsView>
                                </VerticalStackLayout>
                            </Grid>
                        </Frame>
                    </VerticalStackLayout>

                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <ActivityIndicator IsVisible="{Binding IsBusy}"
                           IsRunning="{Binding IsBusy}"
                           HorizontalOptions="FillAndExpand"
                           VerticalOptions="CenterAndExpand"/>
    </Grid>
    
    
</ContentPage>

ScoreGaugeDrawable.cs

namespace MediSkillApp.Drawables;

public class ScoreGaugeDrawable : BindableObject, IDrawable
{
    public static readonly BindableProperty ScoreProperty = BindableProperty.Create(nameof(Score),
        typeof(double),
        typeof(ScoreGaugeDrawable));

    public double Score {
        get => (double)GetValue(ScoreProperty);
        set => SetValue(ScoreProperty, value);
    }

    public void Draw(ICanvas canvas, RectF dirtyRect)
    {
        var centerPoint = new PointF(32, 0);
        var circleRadius = 5;

        canvas.FillColor = Colors.Black;
        canvas.FillCircle(centerPoint, circleRadius);

        canvas.StrokeColor = Colors.Black;
        canvas.DrawLine(centerPoint, new Point(0, Score * 10)); //Just draw something for testing
    }
}

Procedure.cs

namespace MediSkillApp.Model;

public class Procedure
{
    public string Identifier { get; set; }
    public DateTime Date { get; set; }
    public string GetDate {
        get => Date.ToString("d/M-yyyy");
    }

    public int ProcedureType { get; set; }
    public string ProcedureTypeString { get; set; }
    public double AvgScore { get; set; }

    public string GetAvgScore {
        get {
            if (AvgScore == 0) return "";
            return AvgScore.ToString();
        }
    }

    public int OpRole { get; set; }
    public string OpRoleString { get; set; }

    public string Icon {
        get {
            switch (ProcedureType) {
                case 7:
                    return Icons.IconBleed;
                case 8:
                    return Icons.IconTEA;
                case 18:
                    return Icons.IconTEA;
                default:
                    return Icons.IconSurgery;
            }
        }
    }

    public bool IsScored => AvgScore > 0;
}

ProceduresViewModel.cs

using MediSkillApp.Model;
using MediSkillApp.Services;

namespace MediSkillApp.ViewModel;

public partial class ProceduresViewModel : BaseViewModel
{
    public ObservableCollection<Procedure> Procedures { get; } = new();
    private APIService APIservice;

    public ProceduresViewModel(APIService aPIservice) {
        APIservice = aPIservice;
    }

    [RelayCommand]
    public async Task GetProceduresAsync() {
        if(IsBusy) return;

        try {
            IsBusy = true;
            var procedures = await APIservice.GetProceduresAsync("8", "dawda", Procedures.Count, 15);

            foreach (Procedure procedure in procedures) {
                Procedures.Add(procedure);
            }
        } catch(Exception ex) {
            Debug.WriteLine(ex);
        } finally {
            IsBusy = false;
        }
    }

    public void ClearProcedures() {
        Procedures.Clear();
    }
}

推荐答案

我能够重现这个问题.看起来Drawables不能和BindableProperty一起使用,至少它没有任何影响,属性的值不会更新.

然而,我设法找到了解决这个问题的方法.您可以通过继承扩展将其添加到GraphicsView,而不是将Score属性添加到ScoreGaugeDrawable.

您可以从ScoreGaugeDrawable中删除BindableObject基类以及可绑定ScoreProperty,并使用默认的getter和setter将Score属性转换为常规属性:

namespace MediSkillApp.Drawables;

public class ScoreGaugeDrawable : IDrawable
{
    public double Score { get; set; }

    public void Draw(ICanvas canvas, RectF dirtyRect)
    {
        var centerPoint = new PointF(32, 0);
        var circleRadius = 5;

        canvas.FillColor = Colors.Black;
        canvas.FillCircle(centerPoint, circleRadius);

        canvas.StrokeColor = Colors.Black;
        canvas.DrawLine(centerPoint, new Point(0, Score * 10)); //Just draw something for testing
    }
}

然后,创建一个继承自GraphicsViewScoreGraphicsView,并将可绑定的ScoreProperty添加到其中:

namespace MediSkillApp.Drawables;

public class ScoreGraphicsView : GraphicsView
{
    public double Score
    {
        get => (double)GetValue(ScoreProperty);
        set => SetValue(ScoreProperty, value);
    }

    public static readonly BindableProperty ScoreProperty = BindableProperty.Create(nameof(Score), typeof(double), typeof(ScoreGraphicsView), propertyChanged: ScorePropertyChanged);

    private static void ScorePropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is not ScoreGraphicsView { Drawable: ScoreGaugeDrawable drawable } view)
        {
            return;
        }

        drawable.Score = (double)newValue;
        view.Invalidate();
    }
}

这样,需要将分数传递给GraphicsView,它(不幸的是)现在必须知道ScoreGaugeDrawable.这段代码的作用是,它接收对可绑定ScoreProperty的任何更新,并将值传递给ScoreGaugeDrawable.如果值已更改,并且Drawable的类型为ScoreGaugeDrawable,则设置新值,然后使视图无效,这将触发重画.

您可以在XAML中像这样使用ScoreGraphicsViewScoreGaugeDrawable,然后:

<drawables:ScoreGraphicsView
    Score="{Binding AvgScore}">
    <drawables:ScoreGraphicsView.Drawable>
        <drawables:ScoreGaugeDrawable/>
    </drawables:ScoreGraphicsView.Drawable>
</drawables:ScoreGraphicsView>

这并不理想,但应该可以暂时解决您的问题.我自己在我的MAUI Samples存储库中测试了它,它工作得很好.

Csharp相关问答推荐

C#中的多yield 机制

利用.NET 8中的AddStandardResilienceDeliveries和AddStandardHedgingDeliveries实现Resiliency

如何保持主摄像头视角保持一致?

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

. NET在上一个操作完成之前,在此上下文实例上启动了第二个操作

为什么在ANTLR4中会出现不匹配的输入错误?""

共享暂存/生产环境中Azure事件中心的建议配置

Automapper 12.x将GUID映射到字符串

如何将MemberInitExpression添加到绑定中其他Lambda MemberInitExpression

.NET 8在appsettings.json中核心使用词典URI、URI&>

如何从另一个类的列表中按ID取值

单元测试类型为HttpClient with Microsoft.Extensions.Http.Resilience

为什么我的用户界面对象移动到略低于实际目标?

为什么在使用JsonDerivedType序列化泛型时缺少$type?

Azure函数正在返回值列表,但该列表在Chrome中显示为空

为什么我的自定义Json.net转换器不工作?

将两个for循环更改为一条LINQ语句

无法使用直接URL通过PictureBox.ImageLocation加载图像

最小API定义的Swagger标头参数

如何对列表<;列表>;使用集合表达式?