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

后端 未结 3 1463
悲&欢浪女
悲&欢浪女 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-15 23:59

    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

提交回复
热议问题