事件 button.click 发生时如何获取按钮名称/标签? [英] How do you get the button name/tag when the event button.click occurs?

查看:12
本文介绍了事件 button.click 发生时如何获取按钮名称/标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式制作按钮并将它们添加到堆栈面板,以便每次用户导航到页面时按钮都会更改.我正在尝试做这样的事情,当我点击创建的按钮时,它会抓住按钮的标签并转到正确的页面.但是,我无法使用 RoutedEventHandler 访问按钮元素.代码如下:

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

推荐答案

非常简单,只需将发送者强制转换为按钮对象,您将获得所有按钮属性

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

这篇关于事件 button.click 发生时如何获取按钮名称/标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆