简体   繁体   English

如何在Xamarin.Forms中将CommandParameter设置为ListView项本身

[英]How to set the CommandParameter to the ListView item itself in Xamarin.Forms

I'm using a custom ViewCell defined in C# to populate a ListView in Xamarin.Forms. 我正在使用C#中定义的自定义ViewCell来填充Xamarin.Forms中的ListView。 The ViewCell contains an Image, that acts as a button and when clicked, should be able to manipulate the underlying data of the ListView. ViewCell包含一个充当按钮的图像,当单击它时,它应该能够操纵ListView的基础数据。

Basically I am looking for the code behind equivalent for: 基本上我正在寻找等效的背后的代码:

<Image.GestureRecognizers>
    <TapGestureRecognizer                                           
        Command="{Binding Path=BindingContext.PlusClickedCommand, Source={x:Reference Name=ChallengesLV}}"
        CommandParameter="{Binding}"/>
</Image.GestureRecognizers>

I have tried: 我努力了:

plusButton.GestureRecognizers.Add(new TapGestureRecognizer() {
Command = bindingContext.AddProgressToChallengeCommand, 
CommandParameter = new Binding(".")} });

But it gives me an NullReference exception when I try to access the object of type Challenge in my viewmodel like so: 但是当我尝试像这样在我的视图模型中访问Challenge类型的对象时,它给了我一个NullReference异常:

AddProgressToChallengeCommand = new Command( (sender) => doSomething((Challenge)sender) );

When I inspect the sender object in debug mode, it tells me it is an object of type Binding with every property null except path="." 当我在调试模式下检查发送方对象时,它告诉我它是Binding类型的对象,除path =“之外,每个属性都为null。”

How do I get the Item this Binding refers to? 如何获取此绑定所指的项目?

Thanks to Jason: The Command needs to be initialized like that, to access the parameter: 感谢Jason:需要像这样初始化Command才能访问参数:

AddProgressToChallengeCommand = new Command<Challenge>( (challenge) => 
doSomething(challenge);

And for the recognizer binding, I needed to change it to: 对于识别器绑定,我需要将其更改为:

var recognizer = new TapGestureRecognizer() {Command = bindingContext.AddProgressToChallengeCommand};
recognizer.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");
plusButton.GestureRegognizers.Add(recognizer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM