求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:
- Create the TapGestureRecognizer instance
- Bind the Command to your ListView's BindingContext command (matching
{Binding BindingContext.MyId, Source={x:Reference MyList}}) - Bind the CommandParameter to the current item (matching
{Binding .}) - 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
相关产品推荐
相关产品推荐

