【问题标题】:How to set the CommandParameter to the ListView item itself in Xamarin.Forms如何在 Xamarin.Forms 中将 CommandParameter 设置为 ListView 项本身
【发布时间】:2017-12-08 14:53:27
【问题描述】:

我正在使用 C# 中定义的自定义 ViewCell 来填充 Xamarin.Forms 中的 ListView。 ViewCell 包含一个 Image,用作按钮,单击时应该能够操作 ListView 的底层数据。

基本上我正在寻找等效代码背后的代码:

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

我试过了:

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

但是当我尝试在我的视图模型中访问 Challenge 类型的对象时,它给了我一个 NullReference 异常,如下所示:

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

当我在调试模式下检查 sender 对象时,它告诉我它是一个 Binding 类型的对象,除了 path="." 之外的每个属性都为 null。

我如何获得这个 Binding 引用的 Item?

【问题讨论】:

  • 我相信您需要使用 Command 来传递 Challenge 类型的参数 - 发件人不是参数
  • 你说得对,我需要改变它。另外,我需要添加 myTapGestureRecognizer.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");谢谢你的提示!

标签: c# mvvm xamarin.forms code-behind icommand


【解决方案1】:

感谢杰森: 命令需要这样初始化,才能访问参数:

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

对于识别器绑定,我需要将其更改为:

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

【讨论】:

    猜你喜欢
    • 2014-08-21
    • 2014-11-10
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多