Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
It seems that you have bound a list box to a collection, and your buttons are part of your Data Template or Item Template.
You can bind the
Tag
property of the buttons to your data object:
<DataTemplate DataType="{x:Type c:Person}">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock>Name:</TextBlock>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
<Button Click="Button_Click" Tag="{Binding Path=.}">Click me!</Button>
</StackPanel>
</DataTemplate>
And the click event:
private void Button_Click(object sender, RoutedEventArgs e)
Button b = (Button)sender;
Person p = (Person)b.Tag;
MessageBox.Show(p.Name);
But, as other people suggest, you can use the DataContext
property of the Button. It already points to the Person
object in my example.
I think by using the Tag
property, you have more control over what you want to access in you event handler.
There are many ways to do everything! Choose the one that best suits you.
–
lbPersons.DataContext = Persons;
private void person_Clicked(object sender, RoutedEventArgs e) {
Button cmd = (Button)sender;
if (cmd.DataContext is Person) {
Person p = (Person)cmd.DataContext;
And in XAML:
<Window.Resources>
<DataTemplate x:Key="UserTemplate" >
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding Path=Name}" Width="50"/>
<TextBlock Text="{Binding Path=Age}" Width="20"/>
<Button Content="Click" Click="person_Clicked"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox IsSynchronizedWithCurrentItem="True" Name="lbPersons" ItemsSource="{Binding}" ItemTemplate="{StaticResource UserTemplate}" />
</Grid>
ListBox.selectedItem and listbox.SelectedIndex will be set as part of clicking the button.
Assuming the items in the list box are say type MyListBoxItem
void SomeButtonClick(Object sender, EventArgs e)
ListBox lb = sender as ListBox
if (lb != null)
MyListBoxItem item = lb.SelectedItem As MyListBoxItem;
if (item != Null)
item.MethodRelatedToButton(); // maybe
Amplified as requested
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.