ventayol
ventayol

Reputation: 635

UWP ListView Drag item custom UI

I'm building a UWP app using C# and I'm having problems to customize the Drag UI when I'm doing drag & drop for a ListView.

I'm using DragItemsStarting object to set the data I want to drag & drop, but this event doesn't allow to customize the UI.

I've added the DragStarting but it's not being called, so I don't have any chance to modify the Drag UI.

Anyone has found this problem? Any idea on how to customize the Drag UI when using a ListView?

Upvotes: 3

Views: 1363

Answers (2)

Opportunity
Opportunity

Reputation: 31

Maybe you can do it on the ItemTemplate.

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Background="Transparent"
                  CanDrag="True"
                  DragStarting="onDragStarting">
                <!--Content-->
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Upvotes: 1

Yuriy Pelekh
Yuriy Pelekh

Reputation: 308

I'm not sure if I understand you correct and about your particular case and requirements but I would use default reorder behavior in list view:

<ListView x:Name="MyListView" ItemsSource="{Binding Items}" ReorderMode="Enabled" CanReorderItems="True" AllowDrop="True">
...
</ListView>

This code allows you to reorder already existed items in ListView. For adding new items by drag&drop you need to subscribe for Drop event on ListView and add dropped item into your items collection which should be of type ObservableCollection<YourItemType> and assigned/bind to ListView.ItemsSource.

If you still need to customize visual object that you drag&drop you need to subscribe on DragStarting event in this object and set any UI element you want:

private async void OnDragStarting(UIElement sender, DragStartingEventArgs args)
{
    var deferral = args.GetDeferral();
    args.Data.Properties.Add("ItemViewModel", DataContext);

    var renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(uiElementToDrag);

    var buffer = await renderTargetBitmap.GetPixelsAsync();
    var bitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer,
        BitmapPixelFormat.Bgra8,
        renderTargetBitmap.PixelWidth,
        renderTargetBitmap.PixelHeight,
        BitmapAlphaMode.Premultiplied);
    args.DragUI.SetContentFromSoftwareBitmap(bitmap);
    deferral.Complete();
}

uiElementToDrag is visual dragable element of type UIElement.

Upvotes: 1

Related Questions