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)); }; }
Jaredpar
source share