以编程方式绑定按钮

时间:2017-09-17 09:30:18

标签: c# wpf

我有一些像这样的代码:

foreach (Sale s in sales)
{
    StackPanel sp = new StackPanel { Orientation=Orientation.Horizontal };                      
    sp.Children.Add(new TextBlock { Text = s.Model + " " + s.Date.Value.ToShortDateString() });
    sp.Children.Add(new Button { Content = "Удалить", Width = 55, Height = 20,FontSize=13 });//bind to this button
    databaseView.panelSale.Children.Add(new Expander
    {
        Name = "exp" + s.ID,
        Header =sp,
        Content = new SaleView { DataContext = s }
    });
}
break;

和一些方法:

private void DeleteSale(Sale sale)
{
    try
    {
        db.Sales.Remove(sale);
        db.SaveChanges();    
    }
    catch(Exception ex)
    {
        System.Windows.MessageBox.Show(ex.Message);
    }
}

问题是如何将此方法绑定到我以编程方式创建的按钮单击?

2 个答案:

答案 0 :(得分:1)

只需修改此

sp.Children.Add(new TextBlock { Text = s.Model + " " + s.Date.Value.ToShortDateString() });
sp.Children.Add(new Button { Content = "Удалить", Width = 55, Height = 20,FontSize=13 });

   sp.Children.Add(new TextBlock { Text = s.Model + " " + s.Date.Value.ToShortDateString() });
   Button btn = new Button { Content = "Удалить", Width = 55, Height = 20, FontSize = 13 }
   btn.Click += Btn_Click;
   sp.Children.Add(btn);

   //rest of your code
}

private void Btn_Click(object sender, RoutedEventArgs e)
{
   //pass methods or anything in this click event
   //eg:
   DeleteSale(sale); 
   // The above method expects a Sale parameter so pass it appropriately
}

因此,如果您想从Sale循环传递foreach (Sale s in sales),可以执行以下操作:

foreach (Sale s in sales)
{
     //codes above as in your question
     Button btn = new Button { Content = "Удалить", Width = 55, Height = 20, FontSize = 13 }
     btn.Tag = s;
     btn.Click += Btn_Click;
     //codes below as in your question
}

然后在Btn_Click事件中,执行此操作:

private void Btn_Click(object sender, RoutedEventArgs e)
{
   Sale sale = (Sale)((Button)sender).Tag;
   DeleteSale(sale); 
}

希望你明白了。此外,如果您的方法采用参数,您必须考虑到这一点,就像上面的那样

答案 1 :(得分:-1)

您可以使用+=语法和匿名事件处理程序挂钩事件处理程序:

foreach (Sale s in sales)
{
    StackPanel sp = new StackPanel { Orientation = Orientation.Horizontal };
    sp.Children.Add(new TextBlock { Text = s.Model + " " + s.Date.Value.ToShortDateString() });
    Button button = new Button { Content = "Удалить", Width = 55, Height = 20, FontSize = 13 };
    button.Click += (ss, ee) => DeleteSale(s);
    sp.Children.Add(button);
    databaseView.panelSale.Children.Add(new Expander
    {
        Name = "exp" + s.ID,
        Header = sp,
        Content = new SaleView { DataContext = s }
    });
}