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

bal*_*alu 6 xaml swipe-gesture xamarin xamarin.forms

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

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

       swipeGestureRecognizer = new UISwipeGestureRecognizer (() => {
            if (command == null) {
                Console.WriteLine ("No command set");
                return;}
    
            command.Execute (null);
        });
    
    Run Code Online (Sandbox Code Playgroud)

但是我在访问特定行(滑动行)时遇到问题,因此我可以在列表视图中的滑动行上显示/隐藏按钮.请问你能推荐一种方法来实现吗?

小智 5

现在使用ContextAction将滑动删除内置到Xamarin Froms ListViews中.这是如何做到这一点的最基本的教程.它很容易实现.

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

  • xamarin表单实现确实涵盖了最基本的用例.仅供参考:遗憾的是,您无法使用xamarin表单实现向右滑动.您还会遇到根本无法自定义的最基本菜单项(例如,为文本选择不同的字体),这意味着您需要立即开始查看自定义渲染器. (2认同)

mad*_*ode 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;
    }
Run Code Online (Sandbox Code Playgroud)

关键是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;
    }
}
Run Code Online (Sandbox Code Playgroud)