WinUI3中ComboBox添加项时触发COMException(0x8000FFFF)错误求助
WinUI3 可编辑ComboBox按Enter添加项触发异常的解决方法
你遇到的System.Runtime.InteropServices.COMException: 'Catastrophic failure (0x8000FFFF (E_UNEXPECTED))'异常,核心原因是ComboBox已通过ItemsSource绑定了ViewModel的集合,此时不能直接操作Items集合——当设置ItemsSource后,ComboBox的项由绑定的数据源接管,直接调用Items.Add()会触发底层逻辑冲突。
解决步骤:
确保ViewModel中的
Users是可观察集合
只有ObservableCollection能在集合变化时自动通知UI更新,所以ViewModel里的集合定义要改成:public ObservableCollection<string> Users { get; set; } = new ObservableCollection<string>();如果你的
Users是自定义实体类,把string换成对应实体类型即可。修改后台代码,直接操作绑定的数据源
放弃调用userList.Items.Add(),转而向UserViewModel.Users添加项:private void AddUsers(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e) { try { if (e.Key == VirtualKey.Enter) { ComboBox cmb = (ComboBox)sender; string enteredValue = cmb.Text.Trim(); if (!string.IsNullOrEmpty(enteredValue) && !UserViewModel.Users.Contains(enteredValue)) { UserViewModel.Users.Add(enteredValue); cmb.Text = string.Empty; e.Handled = true; // 阻止Enter键的默认选中行为 } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"添加项失败:{ex.Message}"); } }
额外优化说明:
- 加上
Trim()可以去除输入内容的前后空格,避免无效空项。 - 添加重复判断
!UserViewModel.Users.Contains(enteredValue),防止重复添加相同内容。 e.Handled = true会标记事件已处理,避免Enter键触发ComboBox的默认选中逻辑。
内容的提问来源于stack exchange,提问作者Mahesh
相关产品推荐
相关产品推荐

