在 Xamarin 窗体中的网格布局中拖放



我在 XAML 页面中设置了以下网格布局。

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<BoxView BackgroundColor="Red" Grid.Row="0" Grid.Column="0">
<BoxView.GestureRecognizers>
<PanGestureRecognizer PanUpdated="PanGestureRecognizer_OnPanUpdated"/>
</BoxView.GestureRecognizers>
</BoxView>
<BoxView BackgroundColor="Green" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" />
<BoxView BackgroundColor="Red" Grid.Row="0" Grid.Column="3" />
<BoxView BackgroundColor="Blue" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" />
<BoxView BackgroundColor="Purple" Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2"/>
<BoxView BackgroundColor="Aqua" Grid.Row="2" Grid.Column="0" />
<BoxView BackgroundColor="Fuchsia" Grid.Row="2" Grid.Column="1" />
<BoxView BackgroundColor="GreenYellow" Grid.Row="2" Grid.Column="2" Grid.ColumnSpan="2">
</BoxView>
</Grid>

我想在每个框视图上添加拖放功能。这个想法是我应该能够拖动每个框视图并将其放在另一个具有相同列跨度的框视图上。有人可以建议我如何做到这一点吗?请帮忙。

不幸的是,Xamarin.Forms 中还没有内置的拖放功能。您仍然可以使用PanGestureRecognizer自行实现它。

您可以向视图添加手势识别器,例如Label,如下所示:

<Label>
<Label.GestureRecognizers>
<PanGestureRecognizer PanUpdated="PanGestureRecognizer_OnPanUpdated" />
</Label.GestureRecognizers>
</Label>

现在,在PanUpdated事件处理程序中,您可以使用TranslationXTranslationY来移动视图。

private double _startTranslationX, _startTranslationY
private void PanGestureRecognizer_OnPanUpdated(object sender,
PanUpdatedEventArgs e)
{
var box = (BoxView) sender;
if (e.StatusType == GestureStatus.Started)
{
_startTranslationX = box.TranslationX;
_startTranslationY = box.TranslationY;
}
else if (e.StatusType == GestureStatus.Running)
{
box.TranslationX = _startTranslationX + e.TotalX;
box.TranslationY = _startTranslationY + e.TotalY;
}
else if (e.StatusType == GestureStatus.Completed)
{
box.TranslationX = _startTranslationX + e.TotalX;
box.TranslationY = _startTranslationY + e.TotalY;
//handle drop here (depending on your requirements)
}
}

要实际实现拖放功能,您必须手动测试对象当前所在的位置以及是否允许放置。

最新更新