我想通过我的 mainpage.xaml 上的按钮将一个整数列表(称为 buy_player_unit)传递到我的购买单位函数中。我以为我可以使用命令参数...但现在我不确定。
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()
{
this.Unit_list = new ObservableCollection<unit>();
this.player_inst = new player();
}
public ICommand buy_unit_command => new Command(buy_unit);
void buy_unit(object parameter)
{
// i want this function to recieve the buy_player_unit object
Console.WriteLine("buy");
var values = (object[])parameter;
int x = (int)values[0];
int y = (int)values[1];
int team = (int)values[2];
int price = (int)values[3];
Console.WriteLine(this.player_inst.money);
this.player_inst.money -= price;
Unit_list.Add(new unit(x, y, team));
}
public object buy_player_unit()
{
// i want to push this into the buy_unit function
return new object[] { 50, 50, 0, 1 };
}
}
}
下面是我的xml
mainpage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:top_down_rts"
x:Class="top_down_rts.MainPage">
<ContentPage.BindingContext>
<local:units_view_model/>
</ContentPage.BindingContext>
<StackLayout>
<Button
HorizontalOptions="Start"
WidthRequest="200"
Text="buy"
Command="{Binding buy_unit_command}"
CommandParameter="{Binding buy_player_unit}"
/>
</StackLayout>
</ContentPage>
但我得到这个错误
System.NullReferenceException: 'Object reference not set to an instance of an object.'
在这条线上
int x = (int)values[0];
所以我觉得这条线
CommandParameter="{Binding buy_player_unit}"
没有像我希望的那样传入我的对象。
为什么不起作用?我是不是误会了什么?