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

后端 未结 3 1429
悲&欢浪女
悲&欢浪女 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条回答
  •  天涯浪人
    2021-01-16 00:04

    You can get that information from the DataContext.

    public class Person {
    
        public string Name { get; set; }
        public int Age { get; set; }
    
    }
    
     Persons = new ObservableCollection() {
    
          new Person() { Name = "John", Age = 30 },
          new Person() { Name = "Tim", Age = 48 }
     };
    
     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:

    
        
            
                
                
                

提交回复
热议问题