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

Xamarin Form DataGrid更新数据后未自动刷新问题求助

Xamarin.Forms DataGrid 数据更新后不刷新的解决方法

要解决DataGrid不随数据更新刷新的问题,主要检查以下几个关键操作:

  • 实体类必须实现INotifyPropertyChanged接口
    单个数据项的属性变更需要通知UI,所以你的数据模型类得实现这个接口,在属性set方法里触发PropertyChanged事件。可以先写一个通用基类复用:

    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    
    public class ObservableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    

    然后你的数据模型继承这个基类:

    public class Product : ObservableBase
    {
        private string _productName;
        public string ProductName
        {
            get => _productName;
            set
            {
                if (_productName != value)
                {
                    _productName = value;
                    NotifyPropertyChanged();
                }
            }
        }
    
        // 其他属性如Price、StockCount也按这个格式写
    }
    
  • 用ObservableCollection作为数据源
    别用普通的List,它不支持集合变更通知。改用ObservableCollection,当你添加、删除、替换集合里的元素时,它会自动通知DataGrid刷新:

    // 在ViewModel里定义数据源
    public ObservableCollection<Product> Products { get; set; } = new ObservableCollection<Product>();
    

    如果是批量替换数据,直接给ObservableCollection赋值的话,要确保这个属性本身也触发PropertyChanged:

    private ObservableCollection<Product> _products;
    public ObservableCollection<Product> Products
    {
        get => _products;
        set
        {
            _products = value;
            NotifyPropertyChanged();
        }
    }
    
    // 更新时直接赋值新的集合
    Products = new ObservableCollection<Product>(newProductList);
    
  • 检查绑定模式
    确保XAML里DataGrid的ItemsSource绑定设置正确,推荐用TwoWay模式(虽然默认OneWay也能处理集合变更,但TwoWay更保险):

    <DataGrid ItemsSource="{Binding Products, Mode=TwoWay}" />
    
  • 手动触发刷新(极端场景)
    如果以上都做了还是没效果,试试手动强制刷新。比如有些第三方DataGrid控件(比如Syncfusion的)自带Refresh方法:

    myDataGrid.Refresh();
    

    或者通过重置绑定上下文来触发刷新:

    var tempContext = myDataGrid.BindingContext;
    myDataGrid.BindingContext = null;
    myDataGrid.BindingContext = tempContext;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:12