views:

307

answers:

1

I have a ListBox displaying employees with a DataTemplate - it looks very similar to this screenshot. I want to be able to click on the employee photo, drag it and drop it somewhere out of the ListBox. How can I do that? I am not sure how to capture the PreviewMouseLeftButtonDown event of the Image, since it's inside the DataTemplate.

Edit: The DataTemplate lives in a separate assembly and the drag/drop logic needs to be in the Window that has the ListBox.

Edit2: I am thinking that the right way of doing this is using commands, am I right?

Thanks!

A: 

You've not mentioned where the data template is. I'll attempt to cover 2 possibilities both of which are very similar.

If you have the datatemplate in the resource of the user control you can setup events in the code behind file for the user control.

<UserControl.Resources>
    <DataTemplate DataType="{x:Type local:Staff}">
      <StackPanel>
        <TextBlock Text="{Binding Path=Name}"/>
        <Image Name="staffImage" PreviewMouseLeftButtonDown="staffImage_PreviewMouseLeftButtonDown"/>
      </StackPanel>
    </DataTemplate>
</UserControl.Resources>

Then in the UserControl.cs

private void staffImage_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

}

Now if you the datetemplate in a resource dictionary then you can do the exact same thing but you need to create a code behind file for the resource dictionary. See here.

For drag and drop walkthrough itself...See Jamie Rodriguez post here.

Hope that helps.

Crippeoblade
Thanks for your answer but unfortunately it doesn't work for me. I've updated the question regarding where the DataTemplate and the ListBox live. I cannot put logic in the DataTemplate as you suggest. As I see it the DataTemplate dictates how the view should look like and not what it should do. Also, as you can see in my explanation, the view lives in one assembly with a ListBox and other things that I need to "drop" the dragged object into, and the DataTemplate is in a separate assembly
Gustavo Cavalcanti