Xamarin获取按钮点击事件数据在动态listviewdatatemplate



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

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

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
};

相关内容

  • 没有找到相关文章