How to identify the clicked button belongs to which listbox item?

后端 未结 3 1428
悲&欢浪女
悲&欢浪女 2021-01-15 23:45

In WPF programming, I have a problem to write the button click event handler. Because the button is inside a listbox item(a part of datatemplate), and when the button is cli

3条回答
  •  -上瘾入骨i
    2021-01-16 00:17

    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:

    
        
            
                Name:
                
            
            
        
    
    

    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.

提交回复
热议问题