简体   繁体   中英

How to move text from one Textblock to another Textblock using Drag and Drop in a Universal Windows Application?

I know how to set properties like CanDrag and AllowDrop and define DragOver method and Drop method. I just don't know what to write inside the Drop method.

How to move text from one Textblock to another Textblock using Drag and Drop

We can define DragStarting event for the source Textblock and save the text of the source Textblock in DragStartingEventArgs for transfer during dragging. And accept the text when drop at target Textblock . Read the text from DragEventHandler and set it to the target Textblock .

I wrote a simple sample here, move the text from txtsource to append to txttarget .

XAML code:

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="30">
    <Border BorderBrush="Azure" BorderThickness="2">
        <TextBlock x:Name="txtsource" Text="I'm the first textblock" CanDrag="True" DragStarting="txtsource_DragStarting"  />
    </Border>
    <Border BorderBrush="Azure" BorderThickness="2" Margin="20" AllowDrop="True" >
        <TextBlock x:Name="txttarget" Text="I'm the second textblock" Drop="txttarget_Drop"  Height="50" Width="400"  AllowDrop="True" DragEnter="txttarget_DragEnter"/>
    </Border>
</StackPanel>

Code behind

  private void txtsource_DragStarting(UIElement sender, DragStartingEventArgs args)
  {
      args.Data.SetText(txtsource.Text);
  }

  private async void txttarget_Drop(object sender, DragEventArgs e)
  {
      bool hasText = e.DataView.Contains(StandardDataFormats.Text);
      e.AcceptedOperation = hasText ? DataPackageOperation.Copy : DataPackageOperation.None;
      if (hasText)
      {
          var text = await e.DataView.GetTextAsync();
          txttarget.Text +="\n"+ text;
      }
  }
  private void txttarget_DragEnter(object sender, DragEventArgs e)
  {
      bool hasText = e.DataView.Contains(StandardDataFormats.Text);
      e.AcceptedOperation = hasText ? DataPackageOperation.Copy : DataPackageOperation.None;
      if (hasText)
      {
          e.DragUIOverride.Caption = "Drop here to insert text";
      }
  }

I use DragOver event to help define which area can be drop. More details please reference the scenario 2 of the official sample .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM