You can drag from a GridView or a ListView only. Other kinds of controls can act as drop targets. The primary events are OnDragItemsStarting (handled in the drag source) and Drop (handled in the drop target). This code shows the basic steps for dragging
and dropping text. The same pattern applies for other data types. Assume that DragTextSource is a CollectionViewSource that is data-bound to an IVector<MyText^>^ and that MyText has a single string property called SomeText.
<GridView Grid.Row="2" x:Name="DragTextGridView" ItemsSource="{Binding Source={StaticResource DragTextSource}}" CanDragItems="True" DragItemsStarting="DragTextGridView_DragItemsStarting_1">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Border BorderBrush="Azure" BorderThickness="2">
<TextBlock Text="{Binding Path=SomeText}" FontSize="14" Width="200" ></TextBlock>
</Border>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<StackPanel Grid.Row="1">
<Border BorderBrush="Red" BorderThickness="10" Height="120" Width="300">
<TextBlock Height="100" Width="200" x:Name="DropTextHere" FontSize="24" AllowDrop="True" Drop="DropTextHere_Drop_1">Waiting for drop.</TextBlock>
</Border>
</StackPanel>
The event handlers look like this. Basically, when the DragItemsStarting event is fired, the event handler is given a list of items that are being dragged, and an empty DataPackage object. The handler can examine the items being dragged and use that info
to populate the DataPackage. The control that handles the drop event receives the populated Datapackage and extracts its data to perform some custom action. In this case, a TextBlock is the drop target and it just sets its text to the contents of the DataPackage.
void DragDrop3::DragText::DragTextGridView_DragItemsStarting_1(Platform::Object^ sender, Windows::UI::Xaml::Controls::DragItemsStartingEventArgs^ e)
{
auto dp = e->Data;
auto mytxt = safe_cast<MyText^>(e->Items->GetAt(0));
dp->SetText(mytxt->SomeText);
dp->Properties->Description = L"This is just some text I made up.";
}
void DragDrop3::DragText::DropTextHere_Drop_1(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
{
using namespace concurrency; //#include ppltasks.h
auto dataView = e->Data->GetView();
auto getTextTask = create_task(dataView->GetTextAsync());
getTextTask.then([this](String^ txt)
{
DropTextHere->Text = txt;
});
}