9

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));
}

5 Answers 5

15

Pretty simple just cast the sender to a Button Object an you will get all button properties

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

Should work.

4

There are a couple of solutions here. The first is to simple check and see if the sender of the event 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 more type safe / friendly option is to create a lambda to handle the event which 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));
   };
}
3
int tag = (sender as Button).Tag
2

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

Button b = sender as Button; // your logic here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.