拖放一个非文本对象到RichTextBox

本文关键字:文本 对象 RichTextBox 一个 拖放 | 更新日期: 2023-09-27 18:17:57

我试图将非文本对象从标签拖放到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似乎只允许删除文本

拖放一个非文本对象到RichTextBox

来自"Xcalibur37"的代码部分解决了这个确切的问题,在dragOver事件中:

e.Handled = true;

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

您可以在本页查看他的完整答案:在wpf中拖放路径

不需要拖放方法和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);
    }
}