WPF DragDrop 例子
时间: 2023-05-11 21:06:35 浏览: 126
以下是一个简单的 WPF DragDrop 例子:
XAML 代码:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel Orientation="Horizontal" Margin="10">
<TextBlock Text="Drag me:" Margin="0,0,10,0" />
<TextBlock Text="Hello, world!" Background="LightGray" Width="100" Height="50"
PreviewMouseLeftButtonDown="TextBlock_PreviewMouseLeftButtonDown"
PreviewMouseMove="TextBlock_PreviewMouseMove"
PreviewMouseLeftButtonUp="TextBlock_PreviewMouseLeftButtonUp" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10">
<TextBlock Text="Drop here:" Margin="0,0,10,0" />
<Border BorderBrush="Black" BorderThickness="1" Width="100" Height="50"
AllowDrop="True" Drop="Border_Drop" />
</StackPanel>
</Grid>
</Window>
```
C# 代码:
```csharp
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace WpfApp1
{
public partial class MainWindow : Window
{
private bool isDragging = false;
private Point startPoint;
public MainWindow()
{
InitializeComponent();
}
private void TextBlock_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(null);
isDragging = true;
}
private void TextBlock_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (isDragging && e.LeftButton == MouseButtonState.Pressed)
{
Point position = e.GetPosition(null);
Vector offset = startPoint - position;
if (Math.Abs(offset.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(offset.Y) > SystemParameters.MinimumVerticalDragDistance)
{
DataObject data = new DataObject("myFormat", "Hello, world!");
DragDrop.DoDragDrop((DependencyObject)sender, data, DragDropEffects.Copy);
isDragging = false;
}
}
}
private void TextBlock_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
}
private void Border_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
string text = (string)e.Data.GetData("myFormat");
((Border)sender).Child = new TextBlock { Text = text, Background = Brushes.LightGray };
}
}
}
}
```
这个例子演示了如何在 WPF 中实现拖放操作。我们创建了一个包含两个 StackPanel 的 Window,第一个 StackPanel 包含一个 TextBlock,可以被拖动,第二个 StackPanel 包含一个 Border,可以接受拖放操作。当用户按下鼠标左键并移动 TextBlock 时,如果移动距离超过一定阈值,就会触发拖放操作。在拖放操作中,我们将一个字符串放入 DataObject 中,并指定数据格式为 "myFormat"。在 Border 的 Drop 事件中,我们检查数据格式是否为 "myFormat",如果是,就将字符串显示在 Border 中。
阅读全文