使用xamarin将自定义变量传递到命令

g6baxovj  于 2023-05-21  发布在  其他
关注(0)|答案(1)|浏览(172)

我想从mainpage.xaml上的一个按钮向我的buy unit函数传递一个int列表(称为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}"

没有像我希望的那样传入我的对象。
为什么不起作用?我是不是误会了什么?

whlutmcx

whlutmcx1#

CommandParameter需要属性,而不是方法。绑定的buy_player_unit值是一个方法buy_player_unit()
试着用财产来代替

public object buy_player_unit =>
        new object[] { 50, 50, 0, 1 };

或动态计算:

public object buy_player_unit => GetPlayerUnit();

顺便问一下,为什么不能直接在视图模型中使用buy_player_unit呢?而不通过命令参数经由绑定VM通过长链VM-View传递它。
从您的示例中看起来,您可以删除ComandParameter,然后直接从buy_unit_command中访问buy_player_unit,而不需要参数。

相关问题