.NET MAUI CollectionView滚动时RadioButton选中状态异常求助
这个问题是CollectionView的单元格复用机制导致的——为了优化性能,CollectionView只会创建屏幕可见数量的单元格(大概6-7个,对应你看到的重复周期),滚动时旧单元格会被重新绑定到新数据项,如果RadioButton的选中状态没有和数据模型绑定,就会保留之前的选中状态,导致新行出现错误选中。
解决步骤:
给数据模型添加选中状态属性并实现通知
确保你的列表项模型实现INotifyPropertyChanged,并添加一个布尔属性来存储RadioButton的选中状态:public class ListItem : INotifyPropertyChanged { private bool _isSelected; public bool IsSelected { get => _isSelected; set { if (_isSelected != value) { _isSelected = value; OnPropertyChanged(); } } } // 你的其他业务属性,比如选项文本、输入值等 public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); } }在DataTemplate中绑定RadioButton的选中状态
不管是哪个DataTemplate,都要把RadioButton的IsChecked绑定到模型的IsSelected属性,同时确保GroupName设置正确(同一组的RadioButton互斥):<!-- 示例DataTemplate --> <DataTemplate x:Key="Template1"> <HorizontalStackLayout> <RadioButton GroupName="OptionGroup" IsChecked="{Binding IsSelected}" Content="选项A" /> <!-- 其他控件,比如输入框绑定到模型的对应属性 --> <Entry Text="{Binding InputValue}" /> </HorizontalStackLayout> </DataTemplate> <DataTemplate x:Key="Template2"> <HorizontalStackLayout> <RadioButton GroupName="OptionGroup" IsChecked="{Binding IsSelected}" Content="选项B" /> <Entry Text="{Binding InputValue}" /> </HorizontalStackLayout> </DataTemplate>确保ViewModel中的集合项状态独立
初始化列表时,每个ListItem的IsSelected默认设为false,用户选择时通过绑定自动更新对应项的属性,这样滚动时单元格复用会读取新数据项的IsSelected值,不会保留旧状态。
额外注意
如果是多组RadioButton,要给不同组设置不同的GroupName,避免跨组互斥;输入框的文本也要绑定到模型的属性,否则同样会出现滚动时文本复用的问题。
内容的提问来源于stack exchange,提问作者tachidow
相关产品推荐
相关产品推荐

