如何将TapGestureRecognizer添加到StackLayout?

时间:2016-12-18 15:21:06

标签: c# xamarin.forms

所以我有以下代码:

foreach (var a in abc)
{
   var viewCell = new ViewCell 
   { 
      View = new StackLayout()
      {
         //// I want to add TapGestureRecognizer on this outer stacklayout
         Padding = new Thickness(20, 0, 20, 0),
         HorizontalOptions = LayoutOptions.FillAndExpand,
         Children = { 
            new StackLayout() {
               Orientation = StackOrientation.Horizontal,
               VerticalOptions = LayoutOptions.CenterAndExpand,
               Children = {
                  new StackLayout() {
                     HorizontalOptions = LayoutOptions.StartAndExpand,
                     Children = {
                        new Label { Text = a.Name}}
                      },
                  new StackLayout() {
                     HorizontalOptions = LayoutOptions.EndAndExpand,
                     Orientation = StackOrientation.Horizontal,
                     Children = {
                        new Label { Text = a.Count},
                        new Image { Source = "right1.png" }
                     }
                  }
               }
            }
         }
       }
    };
    tableSection.Add(viewCell);
}

这段代码基本上做的是重复我的TableView的行(ViewCell),具体取决于abc中的对象数量。我想在外部添加一个tap事件(第一个Stacklayout),但我似乎无法了解如何使用我的ViewCell设置方式来完成它。任何人都有任何想法?

1 个答案:

答案 0 :(得分:1)

您应首先在变量中创建StackLayout,然后向其中添加TapGestureRecognizer

foreach (var a in abc)
{
   var stackLayout = new StackLayout()
      {
         //// I want to add TapGestureRecognizer on this outer stacklayout
         Padding = new Thickness(20, 0, 20, 0),
         HorizontalOptions = LayoutOptions.FillAndExpand,
         Children = { 
            new StackLayout() {
               Orientation = StackOrientation.Horizontal,
               VerticalOptions = LayoutOptions.CenterAndExpand,
               Children = {
                  new StackLayout() {
                     HorizontalOptions = LayoutOptions.StartAndExpand,
                     Children = {
                        new Label { Text = a.Name}}
                      },
                  new StackLayout() {
                     HorizontalOptions = LayoutOptions.EndAndExpand,
                     Orientation = StackOrientation.Horizontal,
                     Children = {
                        new Label { Text = a.Count},
                        new Image { Source = "right1.png" }
                     }
                  }
               }
            }
         }
       };

   var tgr = new TapGestureRecognizer();
   tgr.Tapped += (s,e) => OnTgrClicked();
   stackLayout.GestureRecognizers.Add(tgr);

   var viewCell = new ViewCell 
   { 
      View = stackLayout;
    };
    tableSection.Add(viewCell);
}