How do you get the button name/tag when the event button.click occurs?

WiteCastle picture WiteCastle · Dec 11, 2013 · Viewed 39.8k times · Source

I'm making buttons programatically and adding them to a stack panel so the buttons change each time the user navigates to the page. I'm trying to do something like this where when I click the created button it'll grab the tag of the button and go to the correct page. However, I can't access the button elements using RoutedEventHandler. Here's the code:

foreach (item in list)
{ 
   Button newBtn = new Button();
   newBtn.Content = "Button Text";
   newBtn.Tag = item.Tag;
   newBtn.Name = item.Name;
   newBtn.Click += new RoutedEventHandler(newBtn_Click);
}

private void newBtn_Click(object sender, RoutedEventArgs e)
{
   NavigationService.Navigate(new Uri("/DetailPage.xaml?selectedItem=" + sender.Tag, UriKind.Relative));
}

Answer

SouthShoreAK picture SouthShoreAK · Dec 11, 2013
(sender as Button).Tag

Should work.