使用Tap Gesture Recognizer从stacklayout获取标签

时间:2017-05-24 10:05:39

标签: c# xaml xamarin xamarin.forms

我想知道用tap手​​势从stacklayout获取不同标签的最佳方法是什么。我的Stacklayout是网格的一部分。

似乎是一个好主意,但没有帮助我获得我的品牌名称的Text值。

继承我的stacklayout的内容:

Image PictureProduct = new Image { Aspect = Aspect.AspectFit };
PictureProduct.Source = FileImageSource.FromUri(...);
Label BrandName = new Label {Text = "HelloWorld"};
Label Description = new Label { Text = "Hello darkness my old friends..."};
Label Price = new Label { Text = "14,99€"};

StackLayout TheStack = new StackLayout { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Fill, HeightRequest = 425 };

TheStack.Children.Add(PictureProduct);
TheStack.Children.Add(BrandName);
TheStack.Children.Add(Description);
TheStack.Children.Add(Price);

var MyTapGesture = new TapGestureRecognizer();

MyTapGesture.Tapped += (sender, e) =>
{

    Debug.Write(/*BrandName of product*/);

};
TheStack.GestureRecognizers.Add(MyTapGesture);

2 个答案:

答案 0 :(得分:1)

我找到了一个目前正在工作的解决方案。

            StackLayout TheStack = new StackLayout { HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Fill, HeightRequest = 425, ClassId = ListProduct[CurrentProd].Sku.ToString(), ClassId = "Something" };

            TheStack.Children.Add(PictureProduct);
            TheStack.Children.Add(BrandName);
            TheStack.Children.Add(Description);
            TheStack.Children.Add(Price);

            var MyTapGesture = new TapGestureRecognizer();
            MyTapGesture.Tapped += (sender, e) =>
            {
                StackLayout TappedStackId = sender as StackLayout;
                Debug.Write("TappedStackId = " + TappedStackId.ClassId);
            };
            TheStack.GestureRecognizers.Add(MyTapGesture);

答案 1 :(得分:0)

您不应将TGR附加到StackLayout,而应附加到每个Label。然后,"发件人"应该告诉你哪个是"发件人" ...

您可以尝试类似

的内容
PictureProduct.GestureRecognizers.Add(MyTapGesture);

MyTapGesture.Tapped += (sender, e) =>
{

    if(sender is PictureProduct){}

};

否则,为每个标签创建一个TGR

PictureProduct.GestureRecognizers.Add(PictureProductTGR);