Reputation: 717
I have a bunch of user controls with buttons on them stored in a listbox. Right now they all pass their button events to a main script and that prints "A button was clicked", it would be better though if it printed "Button D was clicked" as I need to store exactly which buttons were clicked in an array.
Upvotes: 0
Views: 410
Reputation: 1260
The sender parameter in the event call refers to the sending button.
private void btn1_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
}
This might work if the first one does not:
private void btn1_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
}
here's a more generic approach if you only want the listboxitem
private void btn1_Click(object sender, RoutedEventArgs e)
{
object context = (e.OriginalSource as FrameworkElement).DataContext;
var lbi = lb.ItemContainerGenerator.ContainerFromItem(context) as ListBoxItem;
}
see posts: How to select ListBoxItem upon clicking on button in Template? How to retrieve sender in click handler from toolbartray or other control in wpf?
Upvotes: 1
Reputation: 48139
Couldn't you use the CommandParameter of the button and reference that.
Upvotes: 1