I'm trying to know which item is selected/clicked inside a dynamic ListView with a custom buttons inside DataTemplate, trying with some possibilities. I have found one way to know which item has been clicked, creating a label and adding the value to it to identify which item has been selected, but I don't think it's the better way to do it.
Here is some part of my code, any idea how to do it better?
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
};
});
CodePudding user response:
use the BindingContext
turnOnDeviceBtn.Clicked = (o, e) =>
{
var button = (Button)o;
var item = (NodeMCU)button.BindingContext;
// item will be the object bound to the selected row
};