[英]know which button was clicked (Xamarin.Forms)
我有許多像按鈕一樣工作的圖像,這些圖像是通過編程方式創建的,它們的數據來自網絡服務...然后,我不知道會有多少個按鈕。 每個按鈕代表我的Web服務列表中的一個項目...,當單擊按鈕時,我需要知道它代表的項目。 我怎樣才能做到這一點?
我有這樣的東西
而且我需要,當用戶單擊這些圖像之一時,我會收到它代表的對象的名稱...或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,但效果不佳...
您需要將TapGestureRecognizer添加到每個圖像,並將此圖像添加到(可能)網格中。 點擊圖像后,您將在“發送者”參數中收到“圖像”對象。 您可以擴展Image為ID提供新的獲取/設置擴展方法,或從Image派生並添加ID。 您還可以使用設置為“ Source = item.imagem”的Image的Source成員。
我可能會出於以下目的使用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;
};
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.