Lishi
Lishi

Reputation: 402

WPF : Attaching some data to a Button

Problem :

'Im populating a ListView with ControlTemplate. In this template for each item there will be a button that when clicked need to perform some action.

How i can access the object that generated the ListViewItem so i can fetch something (like a id).

Upvotes: 2

Views: 1308

Answers (2)

if you are creating buttons dynamicly , you can use the Tag property for attach your data, or inherit the Button class as My_Button and set a Property wich you need like "userId"

in the other way try watch the Parent property of clicked button.

for example :

private void Button_Click(object sender, RoutedEventArgs e)
        {
          Button clickedButton = sender as Button;
          ListViewItem holderItem = clickedButton.Parent as ListViewItem;
          Console.WriteLine("You are clicked the buton in " + holderItem.Name);
        }

or inline solution:

private void Button_Click(object sender, RoutedEventArgs e)
            {
              Console.WriteLine("You are clicked the buton in " + ((sender as Button).Parent as ListViewItem).Name);
            }

Upvotes: 0

Snowbear
Snowbear

Reputation: 17274

DataContext is your friend. Each list item (and button inside that item if you haven't override button's DataContext) will have a data item which was used to generate the item in DataContext property.

Upvotes: 4

Related Questions