我想通过mainagee.xaml上的一个按钮将一个int列表(称为Buy_PlayerUNIT)传递给我的Buy单元函数.我想我可以使用命令参数.但现在我不确定了.
单位_视图_模型.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}"
没有像我希望的那样传递我的对象.
为什么它不起作用?我是不是听错了什么?