我在wpf中动态创建按钮。比如说btn1
和btn2
:点击按钮时,我想知道点击了哪个按钮?另外,我必须将该按钮id传递给函数。
private void btnAddTimer_Click(object sender, RoutedEventArgs e)
{
int counter =1;
Button dynamicButton = new Button();
dynamicButton.Name = buttonName + counter;//properties of button
dynamicButton.Content = "Toggle";
dynamicButton.Width = 75;
dynamicButton.VerticalAlignment = VerticalAlignment.Top;
dynamicButton.HorizontalAlignment = HorizontalAlignment.Left;
dynamicButton.Margin = new System.Windows.Thickness(80,20,0,0);
}
答案 0 :(得分:0)
这样做的一种方法是使用Tag属性和某种全局计数器来分离动态创建的按钮。
Button dynamicButton = new Button();
dynamicButton.Tag = ++_globalCounter;
然后只需将按钮的Tag属性传递给该函数,然后将其转换为计数器的任何类型,并获得按钮ID。
答案 1 :(得分:0)
向dynamicButton
添加点击处理程序。然后sender
参数为您提供Button实例:
private void btnAddTimer_Click(object sender, RoutedEventArgs e)
{
...
dynamicButton.Click += dynamicButton_Click;
}
private void dynamicButton_Click(object sender, RoutedEventArgs e)
{
var dynamicButton = (Button)sender;
...
}