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;  
        }
    }
posted @ 2024-01-07 17:09  Shepherd_Over  阅读(34)  评论(0编辑  收藏  举报