开发者

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.So开发者_如何转开发urce 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.


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


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.


I think this article will help you. There are part 2 and part 3 as well.

Good luck

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜