问题
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));
}
回答1:
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));
}
回答2:
(sender as Button).Tag
Should work.
回答3:
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));
};
}
回答4:
http://msdn.microsoft.com/en-us/library/windows/apps/hh758286.aspx
Button b = sender as Button; // your logic here
回答5:
int tag = (sender as Button).Tag
来源:https://stackoverflow.com/questions/20530608/how-do-you-get-the-button-name-tag-when-the-event-button-click-occurs