用于自定义控件的Xamarin手势识别器

时间:2018-05-06 16:16:12

标签: android events xamarin.forms command

我创建了一个自定义控件,其中包含一个Image。所以,当用户点击图片时我需要知道。我尝试使用命令添加TapGestureRecognizer,该命令触发了一个事件。但是,这不起作用。我怎么能这样做?

public class PhotoViewer: ContentView
{
   public event Action<object> OnImageClicked;

   public PhotoViewer()
   {
       public PhotoViewer()
       {
           StackLayout stackLayout = new StackLayout();

           IList<View> holders = GeneratePhotoHolders(BackgroundImageCount);
           stackLayout.Children.AddRange(holders);

           this.Content = stackLayout;
       }
   }

    private IList<View> GeneratePhotoHolders(int count)
    {
        List<View> holders = new List<View>();

        for (int i = 0; i < count; i++)
        {
            TapGestureRecognizer OneTapRecognizer = new TapGestureRecognizer()
            {
                NumberOfTapsRequired = 1,
                Command = new Command(o => OnImageClicked?.Invoke(o))
            };
            Image image = new Image();
            image.GestureRecognizers.Add(OneTapRecognizer);

            holders.Add(image);
        }

        return holders;
    }
}

在我的主页内

photoViewer.OnImageClicked += (o) => Debug.WriteLine("Clicked");

EDITED

我已经测试了常见的ConsoleApp上的事件实现,它工作正常。但是,在此自定义控件中,OnImageClicked始终为null

1 个答案:

答案 0 :(得分:0)

我不了解您尝试使用getter返回新实例的目标。我想你想要的是初始化你的吸气剂:

private TapGestureRecognizer OneTapRecognizer { get;} = new TapGestureRecognizer()
      {
         NumberOfTapsRequired = 1,
         Command = new Command<object>(o => OnImageClicked?.Invoke(o))
      };

此外,为什么变量是私有的getter?

我想你真正想要的是:

public class PhotoViewer: ContentView, IDisposable 
{

       private readonly TapGestureRecognizer _oneTapRecognizer;

       public event Action<object> OnImageClicked;

       public PhotoViewer()
       {
           _oneTapRecognizer = new TapGestureRecognizer()
          {
             NumberOfTapsRequired = 1,
             Command = new Command<object>(o => OnImageClicked?.Invoke(o))
            }
           photoHolder.GestureRecognizers.Add(_oneTapRecognizer);
       }

        public void Didpose()
        {
            photoHolder.GestureRecognizers.Remove(_oneTapRecognizer);
        }
   }