0
votes

alt text http://www.freeimagehosting.net/uploads/abbcae9cd3.png

I want to create a listbox like the one shown in the image, i just dont know how will i get the button(the red close button) click event for each item in the listbox Can anyone point me to a good tutorial on this

Thanks

2

2 Answers

2
votes

Create a button as usual, with a Click handler:

<Button Click="MyClickHandler">...</Button>

Now, in your click handler, you have the sender argument, which will contain the button that was clicked. You want the item that the button belongs to, though. First, you need to the ListViewItem that contains the button. There's several implementations of how to find a visual ancestor around, here's the first result I found. Add that extension method to a static class somewhere. So now your click handler looks like this:

private void MyClickHandler(object sender, RoutedEventArgs e)
{
     ListViewItem parent = ((DependencyObject)sender).TryFindParent<ListViewItem>();
}

Now you need to retrieve the item that goes with this ListViewItem. This, thankfully, is much simpler (though I have no idea what it is, since your post doesn't say):

    object ItemRelatedToButton = TheListBoxInQuestion.ItemContainerGenerator.ItemFromContainer(parent);

Replace object with the type that your ListBox actually contains, and the names with ones that are actually relevant. At this point, you can now interact with the item that the button is "attached" to.

You may also want to make sure parent isn't null, just in case something weird happened, and in theory you should make sure ItemRelatedToButton isn't null either.

0
votes

If you don't want to write code behind, like MVVM would suggest, you have two choices: 1. if the control in your datatemplate supports ICommand, send the DataContext as the CommandParameter. Then the parameter will be passed into you command execute method. 2. If the control doesn't have an ICommand property, create an attached property, in the PropertyChangedCallback call back, your can hook a command to your clicked event. Then again, in Xaml you can pass the Datacontext as the CommandParameter.

Sorry for not elaborating further, but if you search for MVVM, Command and Attached, you should find tons of detail informations.