Xamarin 在动态 ListView DataTemplate 中获取按钮单击事件数据

Xamarin get button click event data inside dynamic ListView DataTemplate

我想知道哪个项目是 selected/clicked 在 DataTemplate 中带有自定义按钮的动态 ListView 中,尝试一些可能性。 我找到了一种方法来了解哪个项目已被单击,创建一个标签并向其添加值以标识已选择哪个项目,但我认为这不是更好的方法。

这是我的部分代码,知道如何做得更好吗?

var listView = new ListView();
listView.ItemsSource = await db.GetNodeMCUsAsync();
listView.ItemTemplate = new DataTemplate(() =>
{
    Label llb_id = new Label();
    llb_id.SetBinding(Label.TextProperty, "Id");

    Label lbl_binding = new Label()
    {
        VerticalOptions = LayoutOptions.Center,
        TextColor = Color.Black,
        FontSize = 16,
        Padding = new Thickness(5, 0, 0, 0),
        VerticalTextAlignment = TextAlignment.Start,
        HorizontalOptions = LayoutOptions.Start,
    };
    lbl_binding.SetBinding(Label.TextProperty, "Name");

    var editDeviceBtn = new Button
    {
        Padding = 0,
        Margin = new Thickness(15, 0, 0, 0),
        FontSize = 23,
        TextColor = Color.White,
        FontFamily = "FontIcons",
        Text = "\ue706",
        BackgroundColor = Color.Gray,
        BindingContext = this,
    };
    editDeviceBtn.SetBinding(Button.AutomationIdProperty, "Id");
    
    var turnOnDeviceBtn = new Button
    {
        Padding = 0,
        Margin = new Thickness(15, 0, 0, 0),
        FontSize = 20,
        TextColor = Color.White,
        FontFamily = "FontIcons",
        Text = "\ue703",
        BackgroundColor = Color.Gray,

    };
    turnOnDeviceBtn.SetBinding(Button.AutomationIdProperty, "IP");
    
    editDeviceBtn.Clicked += (o, e) =>
    {
        //NodeMCU obj = ((Button)o).DataContext as NodeMCU;
        //NodeMCU item = (o as Button).DataContext as NodeMCU;
        Navigation.PushAsync(new NodeMCU());
    };
    turnOnDeviceBtn.Clicked += (o, e) =>
    {
        //Only way I found
        var id = lbl_binding.Text;
    };

    var grid = new Grid
    {
        Padding = new Thickness(0, 5),
        ColumnDefinitions = new ColumnDefinitionCollection()
        {
            new ColumnDefinition { Width = new GridLength(.5, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(.25, GridUnitType.Star) },
            new ColumnDefinition { Width = new GridLength(.25, GridUnitType.Star) }
        }
    };
    grid.Children.Add(lbl_binding, 0, 1, 0, 1);
    grid.Children.Add(editDeviceBtn, 1, 2, 0, 1);
    grid.Children.Add(turnOnDeviceBtn, 2, 3, 0, 1);

    return new ViewCell
    {
        View = grid
    };
});

使用BindingContext

turnOnDeviceBtn.Clicked += (o, e) =>
{
    var button = (Button)o;
    var item = (NodeMCU)button.BindingContext;
    // item will be the object bound to the selected row
};