如何在.Net maui Blazor Hybrid中检测滑动手势

slhcrj9b  于 2023-03-20  发布在  .NET
关注(0)|答案(2)|浏览(253)

如何在.NET Maui Blazor Hybrid中检测滑动手势?我在原生.NET Maui中看到过滑动手势示例,但我找不到任何.NET Maui Blazor Hybrid示例。请帮助我

hwamh0ep

hwamh0ep1#

.NET Maui Blazor Hybrid没有内置的滑动手势支持。您可以通过处理各种@ontouch***EventCallback来创建自己的解决方案。下面是一个非常基本的SwipeArea组件实现:

一米四分一秒

<div @attributes="UserAttributes" class="@Class" style="@Style"
     @ontouchstart="OnTouchStart" @ontouchstart:stopPropagation
     @ontouchend="OnTouchEnd" @ontouchend:stopPropagation
     @ontouchcancel="OnTouchCancel" @ontouchcancel:stopPropagation>
    @ChildContent
</div>

@code {
    private double? _xDown;
    private double? _yDown;

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public Action<SwipeDirection> OnSwipe { get; set; }

    [Parameter]
    public string Class { get; set; }

    [Parameter]
    public string Style { get; set; }

    [Parameter]
    public Dictionary<string, object> UserAttributes { get; set; } = new Dictionary<string, object>();

    private void OnTouchStart(TouchEventArgs args)
    {
        _xDown = args.Touches[0].ClientX;
        _yDown = args.Touches[0].ClientY;
    }

    private void OnTouchEnd(TouchEventArgs args)
    {
        if (_xDown == null || _yDown == null)
        {
            return;
        }

        var xDiff = _xDown.Value - args.ChangedTouches[0].ClientX;
        var yDiff = _yDown.Value - args.ChangedTouches[0].ClientY;

        if (Math.Abs(xDiff) < 100 && Math.Abs(yDiff) < 100)
        {
            _xDown = null;
            _yDown = null;
            return;
        }

        if (Math.Abs(xDiff) > Math.Abs(yDiff))
        {
            if (xDiff > 0)
            {
                InvokeAsync(() => OnSwipe(SwipeDirection.RightToLeft));
            }
            else
            {
                InvokeAsync(() => OnSwipe(SwipeDirection.LeftToRight));
            }
        }
        else
        {
            if (yDiff > 0)
            {
                InvokeAsync(() => OnSwipe(SwipeDirection.BottomToTop));
            }
            else
            {
                InvokeAsync(() => OnSwipe(SwipeDirection.TopToBottom));
            }
        }

        _xDown = null;
        _yDown = null;
    }

    private void OnTouchCancel(TouchEventArgs args)
    {
        _xDown = null;
        _yDown = null;
    }
}

滑动方向.cs:

public enum SwipeDirection
{
    None,
    LeftToRight,
    RightToLeft,
    TopToBottom,
    BottomToTop
}

用法示例:

<SwipeArea OnSwipe="OnSwipe" Class="h-100 pt-1">
    @* wrap the area that you want to detect swipe gestures in SwipeArea component *@
</SwipeArea>

@code {
    private SwipeDirection _swipeDirection = SwipeDirection.None;

    private void OnSwipe(SwipeDirection swipeDirection)
    {
        _swipeDirection = swipeDirection;

        // do stuff based on swipe direction
    }
}
xqk2d5yq

xqk2d5yq2#

现在当你在MAUI中使用Blazor时,你可以使用MudBlazor的SwipeArea。刚刚在我的应用程序中测试过,它工作起来很有魅力!

相关问题