将非文本对象拖放到RichTextBox

时间:2011-12-14 19:32:11

标签: c# wpf drag-and-drop richtextbox

我正在尝试将非文本对象从Label拖放到RichTextBox。但是当我将鼠标移到RTB上时,它不允许我放弃。

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            richTextBox1.AllowDrop = true;
            richTextBox1.Drop+=new DragEventHandler(richTextBox1_Drop);
            richTextBox1.DragEnter +=new DragEventHandler(richTextBox1_DragEnter);
            richTextBox1.DragOver+=new DragEventHandler(richTextBox1_DragOver);  

            labelSender.MouseDown+=new MouseButtonEventHandler(labelSender_MouseDown);
        }

        private void richTextBox1_Drop(object sender, DragEventArgs e)
        {
            DropContent dropContent = (DropContent)e.Data.GetData(typeof(DropContent));
            richTextBox1.AppendText(dropContent.Content);
        }

        private void richTextBox1_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
        }

        private void richTextBox1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
        }

        private void labelSender_MouseDown(object sender, MouseEventArgs e)
        {
            DragDrop.DoDragDrop((Label)sender, new DropContent("HelloRichTextBox"), DragDropEffects.Copy);
        }
    }

    public class DropContent //Object containing dragging data
    {
        public string Content;
        public DropContent(string content)
        {
            this.Content = content;
        }
    }

似乎RTB只允许删除文本。

2 个答案:

答案 0 :(得分:0)

解决这个问题的“Xcalibur37”的代码部分在dragOver事件中:

e.Handled = true;

希望它解决其他人的问题,因为它解决了我的问题,这正是最初的问题。

您可以在此页面上查看完整答案:Drag and drop a path in a wpf

答案 1 :(得分:0)

您不需要拖放方法和DropContent类。你只需编写MouseDown方法:

public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();
        richTextBox1.AllowDrop = true;  
        labelSender.MouseDown += new MouseButtonEventHandler(labelSender_MouseDown)
    }

    private void labelSender_MouseDown(object sender, MouseButtonEventArgs e) {
        DragDrop.DoDragDrop((Label)sender, ((Label)sender).Content, DragDropEffects.Copy);
    }
}