I am looping my customers, and for each customer I need to create one button in case I would like to delete that specific customer.
So here is my code:
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);
}
How could I attach event Click on my button so when I click on It I get customer?
void btn_Click(object sender, RoutedEventArgs e)
{
//I tried this but it is not working, unfortunatelly...
Customer cust = (Customer)sender;
}
The easy way: attach customer to the Button.Tag
property
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;
}
What might be better: Create a visual representation of each customer item, where the button is contained. Use Button.Command
and Button.CommandParameter={Binding PathToCustomer}
instead of Button.Click
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.