c#中如何将listview中的项拖拽显示到picturebox背景中?
picturebox无法接收来自listview的字符并且显示字符?想要接收的是listview如图所示的项,然后通过拖拽到picturebox的背景上。本人刚接触c#时间不长,找了一天资料都没有解决,谢谢大家的帮忙。
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
//if (e.Button == MouseButtons.Right) return;
//int nTotalSelected = listView1.SelectedIndices.Count;
// DoDragDrop(e.Item.ToString(), DragDropEffects.Copy);
}
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems == null)
return;
ListViewItem selectedItem = listView1.SelectedItems[0];
listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Copy);
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
}
{ e.Effect = DragDropEffects.None; }
}
private void Form1_Load(object sender, EventArgs e)
{
}
//判断是不是可以接收的类型
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
}
{ e.Effect = DragDropEffects.None; }
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
//把数据显示在picture
string data = (string)e.Data.GetData(typeof(string));
Graphics g = pictureBox1.CreateGraphics();
g.DrawString(data, new Font("Arial", 12), Brushes.Black, 10, 10);
}
listView1.SelectedItems是个集合,不是字符串呀
https://jiuaidu.com/jianzhan/811843/ 参考下
参考GPT和自己的思路:
首先,你需要在 listView1 的 MouseDown 事件中设置 selectedItem 并在 DoDragDrop 方法中传入 selectedItem。在 DragEnter 事件中,你需要判断所传入的数据是否为 string 类型并设置 DragDropEffects,以便 pictureBox1 接收数据。
在 pictureBox1 的 DragEnter 事件中,也需要判断所传入的数据是否为 string 类型并设置 DragDropEffects。在 DragDrop 事件中,可以将所传入的数据进行处理,并将其显示在 pictureBox1 中。
下面是修改后的代码片段。
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems == null)
{
return;
}
ListViewItem selectedItem = listView1.SelectedItems[0];
listView1.DoDragDrop(selectedItem.Text, DragDropEffects.Copy);
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void pictureBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void pictureBox1_DragDrop(object sender, DragEventArgs e)
{
string data = (string)e.Data.GetData(typeof(string));
Graphics g = pictureBox1.CreateGraphics();
g.DrawString(data, new Font("Arial", 12), Brushes.Black, 10, 10);
}
参考链接: