Xamarin表单:在ListView中滑动以删除(手势)

时间:2014-09-17 09:31:00

标签: xaml xamarin swipe-gesture xamarin.forms

我想实现滑动以删除Xamrin Forms中的功能,我已尝试过以下功能。

  1. 为列表视图写了一个自定义渲染器,并在渲染器的“OnElementChanged”中能够访问“CustomListView”的绑定命令,并且能够将此命令添加到滑动手势中,如下所示。

       swipeGestureRecognizer = new UISwipeGestureRecognizer (() => {
            if (command == null) {
                Console.WriteLine ("No command set");
                return;}
    
            command.Execute (null);
        });
    
  2. 但是我在访问特定行(滑动行)时遇到问题,因此我可以在列表视图中的滑动行上显示/隐藏按钮。请问你能推荐一种方法来实现吗?

2 个答案:

答案 0 :(得分:5)

使用上下文操作现在可以在Xamarin Forms ListView中内置滑动以删除。这是如何做到这一点的最基本的教程。它很容易实现。

http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/listview/

答案 1 :(得分:4)

你可以这样做:

    protected override void OnElementChanged (ElementChangedEventArgs<ListView> e)
    {
        base.OnElementChanged (e);
        var swipeDelegate = new SwipeRecogniserDelegate ();
        swipeGestureRecognizer = new UISwipeGestureRecognizer {
            Direction = UISwipeGestureRecognizerDirection.Left,
            Delegate = swipeDelegate
        };
        swipeGestureRecognizer.AddTarget (o => {
            var startPoint = swipeDelegate.GetStartPoint ();
            Console.WriteLine (startPoint);
            var indexPath = this.Control.IndexPathForRowAtPoint(startPoint);
            if(listView.SwipeCommand != null) {
                listView.SwipeCommand.Execute(indexPath.Row);
            }
        });
        this.Control.AddGestureRecognizer (swipeGestureRecognizer);
        this.listView = (SwipableListView)this.Element;
    }

关键是SwipeRecogniserDelegate。它实现如下:

public class SwipeRecogniserDelegate : UIGestureRecognizerDelegate
{
    PointF startPoint;

    public override bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch)
    {
        return true;
    }

    public override bool ShouldBegin (UIGestureRecognizer recognizer)
    {
        var swipeGesture = ((UISwipeGestureRecognizer)recognizer);
        this.startPoint = swipeGesture.LocationOfTouch (0, swipeGesture.View);
        return true;
    }

    public PointF GetStartPoint ()
    {
        return startPoint;
    }
}