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

Xamarin.Forms更新ListView的ItemsSource时内部RadioButton丢失如何解决

问题根因

你当前的RadioButton的选中状态仅保存在控件实例本身,没有和数据源做双向绑定。每次重新赋值ItemsSource时ListView会销毁原有单元格并重新渲染所有项,新生成的RadioButton没有历史选中状态,就会出现清空的情况。

解决方案步骤

步骤1:改造CommonModel,添加状态绑定属性

首先让CommonModel实现INotifyPropertyChanged接口,新增IsChecked属性用来存储RadioButton的选中状态:

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

public class CommonModel : INotifyPropertyChanged
{
    private string _description;
    public string Description
    {
        get => _description;
        set
        {
            _description = value;
            OnPropertyChanged();
        }
    }

    private bool _isChecked;
    public bool IsChecked
    {
        get => _isChecked;
        set
        {
            _isChecked = value;
            OnPropertyChanged();
        }
    }

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

步骤2:修改XAML,绑定RadioButton的选中状态

给RadioButton加上IsChecked的双向绑定,确保用户操作控件时状态能同步回数据源:

<RadioButton BackgroundColor="#ffffff"
             Content="{Binding Description}" 
             IsChecked="{Binding IsChecked, Mode=TwoWay}"
             FontFamily="Roboto" FontSize="16" TextColor="Black"/>

步骤3:优化数据源更新逻辑

不要每次都重新赋值ItemsSource,建议用ObservableCollection<CommonModel>代替List<CommonModel>,增减项时会自动刷新界面,不会触发全量重绘,原有选中状态会自然保留:

// 全局声明数据源
private ObservableCollection<CommonModel> _radioSource = new ObservableCollection<CommonModel>();

// 页面初始化时仅赋值一次ItemsSource
lvRadio.ItemsSource = _radioSource;

// 需要更新数据时直接操作集合即可,无需重设ItemsSource
_radioSource.Clear();
_radioSource.Add(new CommonModel{ Description = "Radio 1" });
_radioSource.Add(new CommonModel{ Description = "Radio 2" });
_radioSource.Add(new CommonModel{ Description = "Radio 3" });

如果确实需要全量替换数据源,提前把旧数据源中各选项的IsChecked状态保存下来,赋值给新数据源对应的项即可。

补充:单选逻辑处理

如果你的RadioButton是单选组,需要选中一个后其他自动取消,直接给RadioButton指定同一个GroupName即可:

<RadioButton GroupName="MyRadioGroup"
             BackgroundColor="#ffffff"
             Content="{Binding Description}" 
             IsChecked="{Binding IsChecked, Mode=TwoWay}"
             FontFamily="Roboto" FontSize="16" TextColor="Black"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:45:03