Xamarin 报错Specified cast is not valid 如何按条件获取Customer类的NameUs值
问题根因
你遇到的两个错误分别对应以下问题:
- 最初的
Specified cast is not valid错误是因为BindingContext绑定的对象类型和你强制转换的ViewProductViewModel不匹配,你后续修改绑定逻辑后已经解决该问题。 - 后续的
Value cannot be null. Parameter name: source错误有两个核心原因:ViewProductViewModel中的Customers属性没有初始化,默认值为null,调用Where方法时传入的数据源为空就会抛出该错误- 即使你初始化了
Customers,也没有触发异步加载客户数据的逻辑,CustomerViewModel中的ExecuteLoadCustomerCommand没有被调用,集合里不会有数据
可行解决方案
步骤1:改造ViewProductViewModel,复用已有的客户数据加载逻辑
直接在ViewProductViewModel中持有CustomerViewModel实例,避免重复写数据加载逻辑,同时保证Customers属性不为空:
public class ViewProductViewModel:BaseProductViewModel { // 复用CustomerViewModel的逻辑和数据 private readonly CustomerViewModel _customerViewModel = new CustomerViewModel(); public ObservableCollection<Customer> Customers => _customerViewModel.Customers; // 暴露加载状态方便后续监听 public bool IsLoading => _customerViewModel.IsBusy; public ViewProductViewModel() { ProductInfo = new ProductInfo(); // 异步触发客户数据加载,不要同步等待避免死锁 _ = LoadCustomerDataAsync(); } private async Task LoadCustomerDataAsync() { if (_customerViewModel.LoadCustomerCommand.CanExecute(null)) { await _customerViewModel.LoadCustomerCommand.ExecuteAsync(null); } } }
步骤2:修改页面逻辑,等待数据加载完成后再查询
因为客户数据是异步加载的,页面构造函数执行时数据还没加载完成,需要监听加载状态,加载完成后再执行查询逻辑,同时加空判断避免空引用:
public Customer _customer { get; set; } public DetailProduct(ProductInfo productInfo) { InitializeComponent(); var productVM = new ViewProductViewModel(); BindingContext = productVM; string idstore = productInfo.StoreID; // 监听加载状态,加载完成后执行查询 productVM.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(productVM.IsLoading) && !productVM.IsLoading) { // 查询前先判空,同时用FirstOrDefault避免匹配不到数据报错 _customer = productVM.Customers?.FirstOrDefault(user => user.PhoneNum == idstore); if (_customer != null) { productInfo.NameStoreID = _customer.NameUs; // 如果需要更新UI,在这里赋值绑定的属性即可 } } }; }
额外优化建议
如果你的应用中多个页面都需要用到客户数据,建议通过依赖注入注入单例的CustomerViewModel实例,避免每个页面都重复请求客户数据,提升性能。
内容的提问来源于stack exchange,提问作者Chim Di Tru
相关产品推荐
相关产品推荐

