You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI项目XAML绑定值异常:Series列未同步更新问题排查

MAUI保龄球计分应用Series总分不更新的修复方案

问题根源

  1. 数据对象无属性变更通知:Games类未实现INotifyPropertyChanged接口,导致对象的Score属性变化时,UI无法感知并刷新。
  2. 绑定未处理类型转换与双向同步:Entry的Text是字符串类型,绑定到int类型的Score时,缺少类型转换处理,且未确保双向绑定的正确性。
  3. 总分计算逻辑未同步输入值:UpdateGame方法中直接读取scores[i].Score时,Entry的输入可能尚未同步到属性,导致计算用的是旧值。

修复步骤

1. 修改Games类,实现属性变更通知

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace HoriView;

public class Games : INotifyPropertyChanged
{
    private string _game;
    private int _score;

    public string Game
    {
        get => _game;
        set
        {
            _game = value;
            OnPropertyChanged();
        }
    }

    public int Score
    {
        get => _score;
        set
        {
            _score = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 优化UpdateGame方法,处理输入转换与总分计算

using System.Collections.ObjectModel;
using System.Linq;

namespace HoriView;

public partial class MainPage : ContentPage
{
    public ObservableCollection<Games> scores { get; set; }
    string header = "Game";

    public MainPage()
    {
        InitializeComponent();
        scores= new ObservableCollection<Games>();
        for(int i=0; i<4; i++)
        {
            header = i == 3 ? "Series" : $"Game {i+1}";
            scores.Add(new Games() 
            { 
                Game=header, 
                Score=0
            });
        }
        BindingContext = this;
    }

    public void UpdateGame(object sender, TextChangedEventArgs e)
    {
        if (sender is Entry entry && entry.BindingContext is Games game && game.Game != "Series")
        {
            // 处理非数字输入,默认赋值为0
            if (int.TryParse(e.NewTextValue, out int score))
            {
                game.Score = score;
            }
            else
            {
                game.Score = 0;
                entry.Text = "0"; // 同步Entry显示内容
            }

            // 计算并更新Series总分
            int totalScore = scores.Take(3).Sum(g => g.Score);
            scores[3].Score = totalScore;
        }
    }
}

3. 调整XAML中Entry的绑定设置

<Entry Grid.Row="1" 
       Text="{Binding Score, Mode=TwoWay, FallbackValue=0}" 
       TextChanged="UpdateGame" 
       Keyboard="Numeric" 
       ReturnType="Next" 
       Placeholder="Game" 
       WidthRequest="83" 
       FontSize="Medium" />

修复效果

完成以上修改后,输入3场比赛的分数时,Series列会实时计算并更新总分,UI会同步刷新;同时处理了非数字输入的异常情况,确保计分逻辑稳定。

内容的提问来源于stack exchange,提问作者Shades49

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:00:16