WPF DragDrop 的拖放 例子
时间: 2023-05-11 09:06:38 浏览: 115
以下是一个简单的 WPF DragDrop 的拖放例子:
XAML 代码:
```xml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="listBox" AllowDrop="True" Drop="listBox_Drop">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
</Grid>
</Window>
```
C# 代码:
```csharp
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void listBox_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.StringFormat))
{
string item = (string)e.Data.GetData(DataFormats.StringFormat);
ListBox listBox = sender as ListBox;
listBox.Items.Add(item);
}
}
private void ListBoxItem_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
ListBoxItem listBoxItem = sender as ListBoxItem;
DragDrop.DoDragDrop(listBoxItem, listBoxItem.Content, DragDropEffects.Copy);
}
}
}
}
```
这个例子演示了如何在 WPF 中实现拖放操作。ListBox 控件允许拖放,当拖动 ListBoxItem 时,会将其内容拖动到 ListBox 中。
阅读全文