Can we set preview of Drag-and-Drop before drag event in WinUI2?

Shyam Butani 355 Reputation points
2025-01-13T12:48:42.26+00:00

Hi,

I'm working on WinUI2 application with Xaml Island in C++. Suppose we've one draggable TextBlock and when we drag it, we can see some preview moving with the mouse pointer moving. In order to set that preview I'm doing in DragStarting handler as shown in below code snippet. Here, I'm showing image as preview when we drag TextBlock.

void DragStarting(UIElement const& sender, DragStartingEventArgs const& args)
{
    winrt::Windows::UI::Xaml::Media::Imaging::BitmapImage bitmapImage;

    bitmapImage.UriSource(winrt::Windows::Foundation::Uri(L"D:/Downloads/car.png"));

    args.DragUI().SetContentFromBitmapImage(bitmapImage);

}

int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow)
{
// ...

	TextBlock text;
	text.Text(L"Drag me");
	text.CanDrag(true);
	text.DragStarting(DragStarting);

	Canvas dropArea;
	dropArea.Width(200);
	dropArea.Height(200);
	dropArea.Background(SolidColorBrush(ColorHelper::FromArgb(255, 0, 255, 0)));  
	dropArea.AllowDrop(true);

	dropArea.DragOver(DragOver);
	dropArea.Drop(Drop);

// ...

}

I want to know if we can set the preview before starting the drag (maybe while creating TextBlock)?

Thanks.

Universal Windows Platform (UWP)
{count} vote

Accepted answer
  1. Junjie Zhu - MSFT 20,026 Reputation points Microsoft Vendor
    2025-01-14T02:20:15.6133333+00:00

    Hello @Shyam Butani ,

    Welcome to Microsoft Q&A!

    DragUI only works when dragging starts. It is not possible to preview before drag-and-drop with DragUI.

    Suppose we've one draggable TextBlock and when we drag it, we can see some preview moving with the mouse pointer moving.

    Depending on your scenario, perhaps we can use other methods to achieve similar effects. It is recommended to use ToolTip to show the preview image. Tooltips display automatically when the user moves focus to, presses and holds, or hovers the pointer over the associated control.

    <TextBlock Text="store logo"> 
          <ToolTipService.ToolTip>
                 <Image Source="Assets/StoreLogo.png"/> 
         </ToolTipService.ToolTip> 
    </TextBlock>
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.