Skip to main content
Home Forums Silverlight Programming Silverlight Controls and Silverlight Toolkit Buttons in Listbox problem
3 replies. Latest Post by mrmop on July 2, 2009.
(0)
mrmop
Member
31 points
51 Posts
07-01-2009 7:54 PM |
I have bound some data to a listbox and each item in the listbox contains a button with a text block at the side. The idea is that when a user clicks one of the buttons, the text in the listbox (along with a few more details) are added to another control. However, when I handle the button click event I cannot figure out which listbox item the button belongs to.
Note that I have considered that the user should firstly select a list box item then click the button and used the selected index, but that seems a bit clunky to me.
This has been driving me crazy all day, can anyone offer a solution?
lingbing
Contributor
2249 points
406 Posts
07-01-2009 10:32 PM |
Hi, the Button class has a default behavior that it will handle MouseLeftButtonDown/Up event and they will not been routed to its parent, so that the ListBoxItem doesn't know the Button is click by users. Then the ListBoxItem will not know user select itself, and the ListBox will not know which item is selected and will not fire SelectionChanged event.
If you use DataBinding to create your items and want to get the SelectedItem object, you can just Binding the source obj to the Button's Tag, it will like:
<ListBox> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding xxx"}/> <Button Content="Click" Tag="{Binding}" Click="Button_Click"/> </StackPanel> </DataTemplate> <ListBox.ItemTemplate><ListBox>
And in xaml.cs code, you can write this in Button_Click handler:
private void Button_Click(object sender, RoutedEventArgs e){ Button b=(Button)sender; object item =b.Tag; //Then do whatever you want by the binding data item}
If you want to get the ListBoxItem and force it to be selected, you can write this code in Button_Click:private void Button_Click(object sender, RoutedEventArgs e){ FrameworkElement element=(FrameworkElement )sender; while(element!=null) { element= VisualTreeHelper.GetParent(element) as FrameworkElement; ListBoxItem item=element as ListBoxItem; if(item!=null) { item.IsSelected=true; break; } }}
Then you can make that ListBoxItem selected.
Regards!
Reeta Lodhi
83 points
16 Posts
07-02-2009 5:30 AM |
you can get the binded data item by using the the DataContext of that button.
private void Button_Click(object sender, RoutedEventArgs e){ myObject obj=((Button)sender).DataContext; //Then do whatever you want by the binding data item}
07-02-2009 6:20 AM |
Thanks that worked great