Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dragging Image into a FlowDocument inside a RichTextBox at runtime

I'm trying to create an editor in WPF 3.5. The functionality which I'm having difficulty with is: I want the user to drag and drop images from a ListBox containing Image objects into the text editor.

I've read the msdn docs about using a FlowDocument inside a RichTextBox inside a ScrollViewer, which I'm using for the editor:

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

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

I have a test Image control to simulate what I intend to put in the ListBox:

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

The code behind looks like this:

    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;
        }
    }

My problem is that the FlowDocument_Drop method never executes and when the image is dragged over the FlowDocument, the cursor still shows that drag is not available.

I don't understand why the event does not fire.

like image 622
annonymously Avatar asked Jun 19 '26 06:06

annonymously


1 Answers

You have to tell the DragOver event that it is handled and not routed to children.

if (e.Data.GetDataPresent("ImageSource")) {
    e.Effects = DragDropEffects.Copy;
    e.Handled = true;
}
like image 80
dwonisch Avatar answered Jun 20 '26 20:06

dwonisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!