Reputation: 575
I have the following grid layout set up in my XAML page.
<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>
I want to add a drag and drop functionality on each box view. The idea is I should be able to drag each box view and drop it on another box view having the same column span. Can someone please advise me on how to do this ? Please help.
Upvotes: 0
Views: 1039
Reputation: 39082
Unfortunately, there is no built-in drag and drop functionality in Xamarin.Forms just yet. You can still implement it yourself using PanGestureRecognizer
.
You can add gesture recognizer to your view, for example Label
, like this:
<Label>
<Label.GestureRecognizers>
<PanGestureRecognizer PanUpdated="PanGestureRecognizer_OnPanUpdated" />
</Label.GestureRecognizers>
</Label>
Now in the PanUpdated
event handler you can use TranslationX
and TranslationY
to move a view around.
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)
}
}
To actually implement a drop functionality you will have to manually test where the object is currently located and if dropping is allowed there.
Upvotes: 1