我在 .NET MAUI 中使用滑动手势得到了一个非常奇怪的行为。方向 Up 和 Down 似乎不起作用,而方向 Right 和 Left 工作得很好。有人知道我做错了什么吗?
这里有一个简单的例子:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SwipeTester.MainPage">
<VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="Center">
<Label x:Name="SwipedCounter" FontSize="18" HorizontalOptions="Center"
BackgroundColor="Yellow" HeightRequest="100" WidthRequest="100"
HorizontalTextAlignment="Center" VerticalTextAlignment="Center"/>
<Label HeightRequest="200"
WidthRequest="100"
BackgroundColor="Red">
<Label.GestureRecognizers>
<SwipeGestureRecognizer
Direction="Down"
Swiped="SwipeGestureRecognizer_OnSwiped"
Threshold="20"/>
<SwipeGestureRecognizer
Direction="Up"
Swiped="SwipeGestureRecognizer_OnSwiped"
Threshold="20"/>
<SwipeGestureRecognizer
Direction="Left"
Swiped="SwipeGestureRecognizer_OnSwiped"
Threshold="20"/>
<SwipeGestureRecognizer
Direction="Right"
Swiped="SwipeGestureRecognizer_OnSwiped"
Threshold="20"/>
</Label.GestureRecognizers>
</Label>
</VerticalStackLayout>
</ContentPage>
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
}
private void SwipeGestureRecognizer_OnSwiped(object sender, SwipedEventArgs e)
{
count++;
SwipedCounter.Text = count.ToString();
}
}
SwipeGestureRecognizer.Direction
属性可以设置为 SwipeDirection
枚举中的单个值,或多个值。
通过将 Direction 属性设置为
Left
和 Right
可以识别发生在水平轴上的滑动。同样,可以通过将 Direction 属性设置为 Up
和 Down
来识别在垂直轴上发生的滑动。
您可以参考下面的示例代码:
<VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="Center">
<Label x:Name="SwipedCounter" FontSize="18" HorizontalOptions="Center"
BackgroundColor="Yellow" HeightRequest="100" WidthRequest="100"
HorizontalTextAlignment="Center" VerticalTextAlignment="Center"/>
<Label HeightRequest="200"
WidthRequest="200"
BackgroundColor="Red">
<Label.GestureRecognizers>
<SwipeGestureRecognizer
Direction="Down"
Swiped="OnSwiped"
Threshold="50"
/>
<SwipeGestureRecognizer
Direction="Up"
Swiped="OnSwiped"
Threshold="50"
/>
<SwipeGestureRecognizer
Direction="Left"
Swiped="OnSwiped"
Threshold="50"
/>
<SwipeGestureRecognizer
Direction="Right"
Swiped="OnSwiped"
Threshold="50"
/>
</Label.GestureRecognizers>
</Label>
</VerticalStackLayout>
void OnSwiped(object sender, SwipedEventArgs e)
{
switch (e.Direction)
{
case SwipeDirection.Left:
SwipedCounter.Text = "left";
break;
case SwipeDirection.Right:
SwipedCounter.Text = "right";
break;
case SwipeDirection.Up:
SwipedCounter.Text = "up";
break;
case SwipeDirection.Down:
SwipedCounter.Text = "down";
break;
}
}