.NET8 MAUI Picker在Android13上为何两次触发选择变更,第二次重置为索引0?
解决.NET MAUI Android 13上Picker选中后自动回滚到索引0的问题
针对你遇到的Picker选中项瞬间重置为索引0的问题,核心原因通常集中在对象相等性判断、绑定冲突或集合稳定性这几个方面,以下是具体的解决步骤:
1. 重写自定义对象的Equals和GetHashCode方法
MAUI的Picker依赖对象的相等性判断来匹配SelectedItem,如果你的MyCustomObject没有正确实现这两个方法,Picker会无法识别选中的对象(即使内容相同,引用不同也会被视为不同项),进而触发自动回滚。
修改MyCustomObject类,基于唯一标识(比如ConfigId这类不可重复的属性)实现相等性判断:
public class MyCustomObject { public int ConfigId { get; set; } // 假设这是唯一标识 public string ConfigName { get; set; } public override bool Equals(object obj) { if (obj is not MyCustomObject other) return false; return ConfigId == other.ConfigId; } public override int GetHashCode() { return ConfigId.GetHashCode(); } }
2. 修复Title绑定的冲突问题
原XAML中Title绑定的是CurrentUserConfig.ConfigName,而SelectedItem绑定的是SelectedUserConfiguration,这两个属性如果不同步,会触发Picker内部状态的异常重置。
将Title绑定到SelectedUserConfiguration的属性,确保选中项和标题状态同步:
<!-- Preconfigured Device Configurations --> <Picker ItemsSource="{Binding UserConfigs}" SelectedItem="{Binding SelectedUserConfiguration, Mode=TwoWay}" <!-- 绑定到选中项的ConfigName,添加FallbackValue避免空值异常 --> Title="{Binding SelectedUserConfiguration.ConfigName, FallbackValue='选择配置'}" TitleColor="{DynamicResource PrimaryTextColor}" ItemDisplayBinding="{Binding ConfigName}" IsEnabled="{Binding ConnectedDevice.Data.LockStatus, Converter={StaticResource LockStatusConverter}}" Grid.Column="1" Margin="10,0,0,0" FontSize="Small" HorizontalOptions="FillAndExpand" HorizontalTextAlignment="Center"/>
3. 确保集合实例的稳定性
如果你的UserConfigs集合在Picker选中后被重新赋值为新的ObservableCollection实例,会导致Picker的ItemsSource被重置,进而选中状态回滚到索引0。
修改ViewModel中UserConfigs的实现,禁止直接赋值,仅通过集合的Clear/Add/Remove方法更新内容:
private readonly ObservableCollection<MyCustomObject> _userConfigs; public ObservableCollection<MyCustomObject> UserConfigs { get => _userConfigs; // 禁止重新赋值集合实例 set => throw new InvalidOperationException("请修改集合内部元素,不要重新赋值"); } public YourViewModel() { // 初始化时创建唯一的集合实例 _userConfigs = new ObservableCollection<MyCustomObject>(); } // 更新集合内容的示例方法 public void UpdateUserConfigs(List<MyCustomObject> newConfigs) { _userConfigs.Clear(); foreach (var config in newConfigs) { _userConfigs.Add(config); } }
4. 显式声明双向绑定(可选但推荐)
虽然MAUI中SelectedItem默认是双向绑定,但显式声明可以避免潜在的绑定模式异常:
SelectedItem="{Binding SelectedUserConfiguration, Mode=TwoWay}"
内容的提问来源于stack exchange,提问作者5coJL
相关产品推荐
相关产品推荐

