Xamarin中CommandParameter传递自定义整数列表参数失败问题
问题分析与解决
问题根源
你遇到的NullReferenceException核心原因是XAML绑定无法直接绑定方法:
- 你在XAML中写的
CommandParameter="{Binding buy_player_unit}",实际绑定的是units_view_model里的buy_player_unit方法本身(一个Func<object>委托),而不是该方法返回的object[]数组。 - 在
buy_unit方法中,你强制将参数转为object[],但实际传入的是方法委托,转换失败后values为null,访问values[0]直接触发空引用异常。
修正方案
把buy_player_unit从方法改成只读属性,让XAML能正确绑定到它返回的数组:
修改后的unit_view_model.cs
namespace top_down_rts { public class units_view_model { public ObservableCollection<unit> Unit_list { get; set; } public player player_inst { get; set; } public units_view_model() { Unit_list = new ObservableCollection<unit>(); player_inst = new player(); } public ICommand buy_unit_command => new Command(buy_unit); void buy_unit(object parameter) { Console.WriteLine("buy"); if (parameter is not object[] values) { // 增加参数校验,避免格式错误引发异常 Console.WriteLine("参数格式错误"); return; } int x = (int)values[0]; int y = (int)values[1]; int team = (int)values[2]; int price = (int)values[3]; Console.WriteLine(player_inst.money); player_inst.money -= price; Unit_list.Add(new unit(x, y, team)); } // 改为只读属性,让XAML可以绑定 public object[] buy_player_unit => new object[] { 50, 50, 0, 1 }; } }
MainPage.xaml无需修改
原XAML绑定逻辑保持不变,现在buy_player_unit是属性,能被正确解析:
<Button HorizontalOptions="Start" WidthRequest="200" Text="buy" Command="{Binding buy_unit_command}" CommandParameter="{Binding buy_player_unit}" />
额外优化建议
- 保留
buy_unit方法中的参数类型校验逻辑,避免后续因参数格式错误再次抛出异常。 - 如果需要根据玩家状态动态生成数组,可以让
units_view_model实现INotifyPropertyChanged接口,在数组内容变化时触发属性变更通知,保证UI能同步更新。
内容的提问来源于stack exchange,提问作者tgmjack
相关产品推荐
相关产品推荐

