TextBox文件拖动事件
在WPF
中若要实现文件拖动,需要注册以下两个事件:
PreviewDragOver
Drop
注意:
TextBox
注册DragOver
事件可能无法实现文件拖动事件
public class TextBoxDropBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
// 注册事件
AssociatedObject.PreviewDragOver += FileDragOver;
AssociatedObject.Drop += FileDrop;
}
// 移除事件
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Drop -= FileDrop;
AssociatedObject.PreviewDragOver -= FileDragOver;
}
private void FileDrop(object sender, DragEventArgs e)
{
AssociatedObject.Text =
((string[])e.Data.GetData(DataFormats.FileDrop))[0].ToString();
}
private void FileDragOver(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
}