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

Xamarin.Forms中ObservableCollection内元素属性变更时如何更新UI

问题根本原因

ObservableCollection<T> 仅会在集合元素新增、删除、替换、重排时触发变更通知,集合内单个元素的属性变更需要元素自身实现INotifyPropertyChanged接口才能被Xamarin.Forms绑定系统感知,从而实时更新UI。


推荐解决方案:实现INotifyPropertyChanged接口

这是符合MVVM规范的标准实现,修改CategoryType类代码如下:

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

public class CategoryType : INotifyPropertyChanged
{
    // 变更通知事件
    public event PropertyChangedEventHandler PropertyChanged;

    // 触发变更通知的辅助方法
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _title;
    public string title
    {
        get => _title;
        set 
        { 
            _title = value;
            OnPropertyChanged();
        }
    }

    private int _tblCategoryID;
    public int tblCategoryID
    {
        get => _tblCategoryID;
        set 
        { 
            _tblCategoryID = value;
            OnPropertyChanged();
        }
    }

    private string _backgroundColor = "#2C2E31";
    public string backgroundColor
    {
        get => _backgroundColor;
        set 
        { 
            _backgroundColor = value;
            OnPropertyChanged();
        }
    }

    private bool _isSelected;
    public bool isSelected
    {
        get => _isSelected;
        set 
        { 
            _isSelected = value;
            OnPropertyChanged();
        }
    }
}

修改完成后你原有的点击事件代码不需要做任何调整,只要XAML中Frame的BackgroundColor绑定没有显式设置为OneTime,属性变更就会实时同步到UI。


临时替代方案(不符合MVVM规范,仅应急使用)

如果暂时不想调整Model类定义,可以在点击事件中直接操作UI控件强制刷新:

void TapGestureRecognizer_Tapped(System.Object sender, System.EventArgs e)
{
    var item = sender as Xamarin.Forms.Frame;
    var model = item.BindingContext as CategoryType;

    if (model.isSelected)
    {
        model.backgroundColor = "#2C2E31";
        model.isSelected = false;
        item.BackgroundColor = Color.FromHex("#2C2E31");
    }
    else
    {
        model.isSelected = true;                 
        model.backgroundColor = "#60CED3";
        item.BackgroundColor = Color.FromHex("#60CED3");
    }
    item.ForceUpdateSize();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:36:00