You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Xaml中CommandParameter="{Binding .}"对应的C#等效实现方式

Sure thing! Here's how you can recreate that XAML gesture recognizer setup entirely in C# code, which will pass the full MyClass object to your command just like the XAML version does.

Step-by-Step C# Equivalent

Let's break down the code to match your original XAML line for line:

  1. Create the TapGestureRecognizer instance
  2. Bind the Command to your ListView's BindingContext command (matching {Binding BindingContext.MyId, Source={x:Reference MyList}})
  3. Bind the CommandParameter to the current item (matching {Binding .})
  4. Add the gesture to your Label's GestureRecognizers collection

Here's the concrete code:

// Assume you have references to your Label (myLabel) and ListView (myList)
var tapGesture = new TapGestureRecognizer();

// Bind the Command - mirrors the XAML's Command binding
tapGesture.SetBinding(
    TapGestureRecognizer.CommandProperty,
    new Binding(
        path: "BindingContext.MyId",
        source: myList // This replaces the x:Reference to your ListView
    )
);

// Bind the CommandParameter to pass the full MyClass object
tapGesture.SetBinding(
    TapGestureRecognizer.CommandParameterProperty,
    new Binding(".") // The "." refers to the current DataContext (your MyClass instance)
);

// Add the gesture to the Label
myLabel.GestureRecognizers.Add(tapGesture);

If You're Building the ItemTemplate in Code

If you're defining your ListView's ItemTemplate entirely in C# (instead of XAML), here's how you'd integrate this gesture setup:

var itemTemplate = new DataTemplate(() =>
{
    var label = new Label();
    // Optional: Bind the Label's Text to a property on MyClass
    label.SetBinding(Label.TextProperty, "YourPropertyName");

    var tapGesture = new TapGestureRecognizer();
    // Bind the command to the ListView's BindingContext command
    tapGesture.SetBinding(
        TapGestureRecognizer.CommandProperty,
        new Binding("BindingContext.MyId", source: MyList)
    );
    // Pass the full MyClass object as the command parameter
    tapGesture.SetBinding(TapGestureRecognizer.CommandParameterProperty, new Binding("."));

    label.GestureRecognizers.Add(tapGesture);
    return label;
});

// Assign the template to your ListView
MyList.ItemTemplate = itemTemplate;

This code behaves exactly like your original XAML: when the Label is tapped, the MyId command will receive the full MyClass object associated with that ListView item as its parameter.

内容的提问来源于stack exchange,提问作者Pranay Deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:48:16