拖放不起作用
问题描述:
我有用WCF创建的上传/下载Web服务。我用c sharp作为语言。拖放不起作用
我允许在我的文本框中启用drop,它接受要拖入其中的项目,但它不允许我这样做,我仍然没有看到悬停在它上面的符号。
有什么,我失踪? 仅供参考我使用完全相同的代码制作了另一个程序,我能够拖放项目没有问题。
private void FileTextBox_DragEnter(object sender, DragEventArgs e)
{
//Makes sure that the user is dropping a file, not text
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
//Allows them to continue
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void FileTextBox_DragDrop(object sender, DragEventArgs e)
{
String[] files = (String[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
FileTextBox.Text = file.ToString();
}
}
答
这些不是您需要的唯一代码。你将需要:
FileTextBox.AllowDrop = true;
FileTextBox.DragEnter += new DragEventHandler (FileTextBox_DragEnter);
FileTextBox.DragDrop += new DragEventHandler (FileTextBox_DragDrop);
当然,如果您使用的是IDE,您可以通过在窗体设计器分配处理器实现这一目标。
答
'正常'DragEnter
,DragOver
,Drop
,...事件不适用于TextBox!改为使用PreviewDragEnter
,PreviewDragOver
,PreviewDrop
!
还要确保在PreviewDragOver和/或PreviewDragEnter委托中设置了DragDropEffects
!
小例如:删除一个文件夹以文本框
XAML部分:
<TextBox
Text=""
Margin="12"
Name="textBox1"
AllowDrop="True"
PreviewDragOver="textBox1_DragOver"
PreviewDragEnter="textBox1_DragOver"
PreviewDrop="textBox1_Drop"/>
代码隐藏部分:
private void textBox1_DragOver(object sender, DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] filenames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
if(filenames.Count() > 1 || !System.IO.Directory.Exists(filenames.First()))
{
e.Effects = DragDropEffects.None;
e.Handled = true;
}
else
{
e.Handled = true;
e.Effects = DragDropEffects.Move;
}
}
}
private void textBox1_Drop(object sender, DragEventArgs e)
{
var buffer = e.Data.GetData(DataFormats.FileDrop, false) as string[];
textBox1.Text = buffer.First();
}
'TextBox'不是合适的控制通过一个循环添加到。获取第一个文件或使用列表控件。 – Homam 2011-03-24 00:00:55
我认为你的意思是WPF不是WCF。 – DuckMaestro 2011-03-24 01:27:40