views:

581

answers:

2

Following from my question on binding in general, I'd like to ask for help on the following scenario.

I have a collection of objects (imageFileData) displayed via a DataTemplate in a ListBox control. The control is bound to an ObservableCollection. Both the collection and the template are defined within my application xaml and xaml.cs files. Dynamic addition of items to the collection works as expected, and displays a new templated item in my listbox. Good.

One of the things I want to be able to do is to remove a specific item from the collection by clicking a button defined in the DataTemplate. Defining a Click handler for the button allows me to handle the event, but I have no idea where to get the imageFileData object that relates to the templated button. My event handler for the button obviously passes the button as the sender, and a set of RoutedEventArgs, but I can't figure out how to relate this data back to an item from the collection in order to allow me to remove it.

Can anyone help me with that, or am I doomed to awkward and fruitless Google searches because I don't know where to start? ;)

Thanks ZS

+3  A: 

The data used to generate the item would be in the Button's DataContext (which it inherited from the container - a ListBoxItem in your case):

private void ButtonClicked(object sender, EventArgs e)
{
    var button = sender as Button;
    var imageFileData = button.DataContext as ImageFileData;

    ...
}

HTH, Kent

Kent Boogaart
Kent, you are a star - saved me from a weekend of wondering what the heck to do to find the answer. Thanks.
ZombieSheep
You're welcome. Enjoy your weekend!
Kent Boogaart
A: 

An other way would be to walk the visual tree up to a ListBoxItem (containing all the elements you defined in the datatemplate). When you have the ListBoxItem containing the clicked button, you can easily get and delete the data of the ListBoxItem.

An example of walking the visual tree upwards is found here: Marlongrech in GetObjectDataFromPoint and here: wpftutorial.net/DragAndDrop in FindAncestor

Loy