Reputation: 767
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));
}
Upvotes: 9
Views: 48605
Reputation: 1504
http://msdn.microsoft.com/en-us/library/windows/apps/hh758286.aspx
Button b = sender as Button; // your logic here
Upvotes: 2
Reputation: 754545
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));
};
}
Upvotes: 4
Reputation: 13755
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));
}
Upvotes: 15