我有许多像按钮一样工作的图像,并以编程方式创建,他们的数据来自网络服务......然后,我不知道我将拥有多少按钮。每个Button代表我的webservice列表中的一个项目......并且,当单击该按钮时,我需要知道它代表哪个项目。我怎么能这样做?
我有类似的东西
我需要,当用户点击其中一个图像时,我会收到它所代表的对象的名称......或者是一个ID ......我不知道......
我用这段代码创建它:
void eteste()
{
int column = 0;
int row = 0;
lstCategorias = lstCategorias.OrderBy(o => o.nome).ToList();
foreach (var item in lstCategorias)
{
StackLayout stack = new StackLayout();
stack.VerticalOptions = LayoutOptions.Center;
Image textura = new Image();
textura.Source = "pngteste";
textura.AutomationId = item.idCategoria;
textura.HorizontalOptions = LayoutOptions.Fill;
textura.VerticalOptions = LayoutOptions.Fill;
gridteste.Children.Add(new BoxView { Color = Color.FromHex(item.corFundo) }, row, column);
gridteste.Children.Add(textura, row, column);
var CliqueCategoria = new TapGestureRecognizer();
CliqueCategoria.Tapped += (s, e) => {
};
textura.GestureRecognizers.Add(CliqueCategoria);
gridteste.Children.Add(stack, row, column);
stack.Children.Add(new Image { Source = item.imagem, VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Fill });
stack.Children.Add(new Label { Text = item.nome, TextColor = Color.FromHex(item.corTexto), BackgroundColor = Color.Accent, VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand });
if (row == 0)
{
row = 1;
}
else
{
row = 0;
column++;
}
}
}
我尝试在foreach中使用 textura.AutomationId = item.id 以获取后面的ID ...并且我使用了 CliqueCategoria.Tapped + =(s,e )=> 使用** var x = s.AutomationId **,尝试获取按钮所代表的项目的ID,但它也不起作用...
答案 0 :(得分:2)
您需要将TapGestureRecognizer添加到每个图像,并将此图像添加到(可能)Grid。轻触图像时,您将在“sender”参数中收到“Image”对象。您可以扩展图像,为Id提供新的get / set扩展方法,或者从Image派生并添加Id。您还可以使用您设置为“Source = item.imagem”
的Image的Source成员答案 1 :(得分:0)
我可能会将BindingContext
属性用于此目的:
foreach (var item in lstCategorias)
{
...
Image textura = new Image();
textura.BindingContext = item;
...
var CliqueCategoria = new TapGestureRecognizer();
CliqueCategoria.Tapped += (s, e) => {
var image = s as Image;
var itemFrom_lstCategorias = image.BindingContext as TypeOfTheItemFromForeach;
};
...
}