c# - 在运行时将图像拖到 RichTextBox 内的 FlowDocument 中

标签 c# wpf image xaml drag-and-drop

我正在尝试在 WPF 3.5 中创建一个编辑器。我遇到困难的功能是:我希望用户将图像从包含 Image 对象的 ListBox 拖放到文本编辑器中。

我读过 msdn docs关于在 ScrollViewer 中的 RichTextBox 中使用 FlowDocument,我将其用于编辑器:

<ScrollViewer>
    <RichTextBox>
        <FlowDocument AllowDrop="True" Drop="FlowDocument_Drop" DragOver="FlowDocument_DragOver">

        </FlowDocument>
    </RichTextBox>
</ScrollViewer>

我有一个测试 Image 控件来模拟我打算放入 ListBox 中的内容:

<Image Grid.Row="0" Name="img" Source="test.png"
           MouseMove="img_MouseMove" />

后面的代码是这样的:

    private void img_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            DragDrop.DoDragDrop(sender as DependencyObject,
                new DataObject("ImageSource", (sender as Image).Source), DragDropEffects.Copy);
        }
    }

    private void FlowDocument_Drop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent("ImageSource"))
        {
            ImageSource img = (ImageSource)e.Data.GetData("ImageSource");

            (sender as FlowDocument).Blocks.Add(new BlockUIContainer(new Image() { Source = img }));
        }
    }

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

        if (e.Data.GetDataPresent("ImageSource"))
        {
            e.Effects = DragDropEffects.Copy | DragDropEffects.Move;
        }
    }

我的问题是 FlowDocument_Drop 方法永远不会执行,当图像被拖动到​​ FlowDocument 上时,光标仍然显示拖动不可用。

我不明白为什么事件没有触发。

最佳答案

您必须告诉 DragOver 事件它已被处理并且未路由到子级。

if (e.Data.GetDataPresent("ImageSource")) {
    e.Effects = DragDropEffects.Copy;
    e.Handled = true;
}

关于c# - 在运行时将图像拖到 RichTextBox 内的 FlowDocument 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9042561/

相关文章:

c# - 使用 C# 在 Skype 上错过聊天

c# - 数据上下文。有没有一种方法可以在其中添加额外的 WHERE?

wpf - 文本框密码字符

c# - 从数据库检查登录凭据

HTML : Is there any way to show images in a textarea?

css - <img/> 与背景图片

c# - Asp.NET MVC 4 WebApi 升级 - RC 到 4.0.30506.0

c# - 如何模拟 gremlin 服务器或创建内存图以进行单元测试?

WPF:无法使用 FindName 访问 ComboBox 的 TextBox

css float 图像似乎不起作用