单击事件以编程生成的XAML按钮

时间:2015-07-22 20:05:06

标签: c# xaml

我是以编程方式生成一个表格,其中Text2列是一个按钮:

for (int i = 0; i < workPackages.Length; i++)
{
    //Define new Row to add
    RowDef = new RowDefinition();
    RowDef.Height = new GridLength(60);

    //Add row definition to Grid
    WorkPackageResults.RowDefinitions.Add(RowDef);

    //Define the control that will be added to new row
    Text1 = new TextBlock();
    Text1.Text = workPackages[i].EWPStatus;
    Text1.Width = 100;
    Text1.TextAlignment = TextAlignment.Center;

    Text2 = new Button();
    Text2.Content = workPackages[i].EWPCode;
    Text2.Width = 300;

    Text3 = new TextBlock();
    Text3.Text = workPackages[i].Description;
    Text3.Width = 500;
    Text3.TextAlignment = TextAlignment.Center;

    Text4 = new TextBlock();
    Text4.Text = workPackages[i].ForeBadge;
    Text4.Width = 100;
    Text4.TextAlignment = TextAlignment.Center;

    //create stackpanel and define which row to add the stackpanel to
    StackP = new StackPanel();
    StackP.SetValue(Grid.RowProperty, i);
    StackP.Orientation = Orientation.Horizontal;
    StackP.Margin = new Thickness(50, 0, 0, 0);

    //add your control to the stackpanel
    StackP.Children.Add(Text1);
    StackP.Children.Add(Text2);
    StackP.Children.Add(Text3);
    StackP.Children.Add(Text4);

    //add the stackpanel to the grid
    WorkPackageResults.Children.Add(StackP);
} 

enter image description here

如何以编程方式添加点击事件?当执行click事件时,如何知道它来自哪个按钮?

1 个答案:

答案 0 :(得分:1)

向Text2.Click添加一个事件处理程序,它将传递发件人作为参数,这就是你知道点击了哪一个。