按钮单击(动态创建按钮) - 堆栈面板获取对象/项目

时间:2017-01-25 08:31:11

标签: c# wpf button stackpanel

我正在循环我的客户,对于每个客户,我需要创建一个按钮以防万一 我想删除该特定客户。

所以这是我的代码:

foreach (var item in customersList)
{
    Button btn = new Button();
    btn.Content = "Customer": + " " + item.Value;
    btn.Height = 40;
    btn.Click += btn_Click;

    TextBox cust = new TextBox();
    cust.Height = 40;
    cust.Text = item.Value;

    stackCustomers.Children.Add(cust);
    stackCustomers.Children.Add(btn);
}

我如何附加活动点击我的按钮,这样当我点击它时我得到了客户?

void btn_Click(object sender, RoutedEventArgs e)
{     
    //I tried this but it is not working, unfortunatelly...
    Customer cust = (Customer)sender;
}

1 个答案:

答案 0 :(得分:1)

简单方法:将客户附加到Button.Tag属性

Button btn = new Button();
btn.Tag = item; // .Value maybe?

// ...

void btn_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    Customer cust = (Customer)button.Tag;
}

可能更好:创建每个客户项目的可视化表示,其中包含按钮。使用Button.CommandButton.CommandParameter={Binding PathToCustomer}代替Button.Click