简体   繁体   中英

WPF C# Drag & Drop Events

I have a canvas that I drop some tools onto to create a diagram (this resides in tabitem2).

What I'm looking to do is when a tool is dropped on the canvas is associate an event that spits out text to a textbox (located in tabitem3).

XAML:

<ListBox>
        <ListBox.Resources>
            <Style TargetType="{x:Type Image}">
                <Setter Property="Width" Value="100"/>
                <Setter Property="Height" Value="100"/>
                <EventSetter Event="MouseLeftButtonDown" Handler="DragImage"/>
            </Style>
        </ListBox.Resources>
        <ListBoxItem>
            <Image Source="toolitem1.png"></Image>
        </ListBoxItem>
    </ListBox>
 <Canvas x:Name="Canvas" AllowDrop="True" Background="Aqua" Drop="DropImage"/>

Code Behind:

private void DragImage(object sender, MouseButtonEventArgs e)
    {

        Image image = e.Source as Image;
        DataObject data = new DataObject(typeof(ImageSource), image.Source);
        DragDrop.DoDragDrop(image, data, DragDropEffects.Copy);

    }


    private void DropImage(object sender, DragEventArgs e)
    {
        ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
        Image imageControl = new Image() { Width = image.Width, Height = image.Height, Source = image };
        Canvas.SetLeft(imageControl, e.GetPosition(this.Canvas).X);
        Canvas.SetTop(imageControl, e.GetPosition(this.Canvas).Y);
        this.Canvas.Children.Add(imageControl);
}

UPDATE:

Added some sample code and tried the suggestions from the folks below to no avail. It looks like when I try to use DragDrop.Drop in my ListBoxItem object it will override the DropImage event for my canvas so I'm still stuck.

have you looked at the drop event ? basiclly, in .net/wpf 4, there is a DragDrop class to help with these matters. Here is the MSDN documentation on the matter.

[EDIT]

From what I am seeing, you are dragging/dropping an image. I think what you need to do is, instead, make some custom object that holds your image AND some data. if you make the image a dependency property, you can bind to that in your listbox item, and then in your drop event, access the other properties in order to get the data that you want.

there is only one event for each drop target. whatever source-related info you want to leverage in that handler should be passed as part of the data parameter to DoDragDrop

I thinkthis article will help you. There arepart 2 andpart 3 as well.

Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM