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

I make buttons programmatically and add them to the stack panel so that the buttons change every time a user navigates to a page. I try to do something like this when, when I click the Create button, it grabs the button tag and goes to the correct page. However, I cannot access button elements using RoutedEventHandler. Here is 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)); } 
+7
c # visual-studio-2013 windows-phone wpf windows-phone-8
source share
5 answers

It’s quite simple to simply give the sender to the Button object and you’ll get all the properties of the buttons

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

Must work.

+9
source share

There are several solutions here. Firstly, this is a simple check and see if the event sender was a Button element and use the information there

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

Another type of safe / friendly option is to create a lambda to handle an event that directly accesses the Button instance you want

 foreach (item in list) { Button newBtn = new Button(); newBtn.Content = "Button Text"; newBtn.Tag = item.Tag; newBtn.Name = item.Name; newBtn.Click += (sender, e) => { NavigationService.Navigate(new Uri("/DetailPage.xaml?selectedItem=" + newBtn.Tag, UriKind.Relative)); }; } 
+4
source share

http://msdn.microsoft.com/en-us/library/windows/apps/hh758286.aspx

Button b = sender as a button; // Your logic is here

+2
source share
 int tag = (sender as Button).Tag 
+1
source share

All Articles