单击按钮时获取 object/item(动态创建的按钮)- 堆栈面板
Get object/item on button click (dynamically created button) - stack panel
我正在循环我的客户,我需要为每个客户创建一个按钮以防万一
我想删除那个特定的客户。
所以这是我的代码:
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;
}
简单的方法:将客户附加到 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.Command
和 Button.CommandParameter={Binding PathToCustomer}
而不是 Button.Click
.
我正在循环我的客户,我需要为每个客户创建一个按钮以防万一 我想删除那个特定的客户。
所以这是我的代码:
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;
}
简单的方法:将客户附加到 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.Command
和 Button.CommandParameter={Binding PathToCustomer}
而不是 Button.Click
.