优化:具有相同代码但不同值的多个clickevents

时间:2016-11-20 19:21:04

标签: mouseclick-event

我的代码如下。是否可以更有效地写出这个?因为我重复了代码,所以Drank类只有其他值。

 private void btnCola_Click(object sender, RoutedEventArgs e)
    {
        Drank dranken = new Drank
        { Naam = "Cola", Prijs = 1.50M };
        lblDrankje.Content = dranken.ToString();
        GroupBox1.IsEnabled = false;
    }

    private void btnWater_Click(object sender, RoutedEventArgs e)
    {
        Drank dranken = new Drank
        { Naam = "Water", Prijs = 1.00M };
        lblDrankje.Content = dranken.ToString();
        GroupBox1.IsEnabled = false;
    }

    private void btnKoffie_Click(object sender, RoutedEventArgs e)
    {
        Drank dranken = new Drank
        { Naam = "Koffie", Prijs = 1.70M };
        lblDrankje.Content = dranken.ToString();
        GroupBox1.IsEnabled = false;
    }

    private void btnSoep_Click(object sender, RoutedEventArgs e)
    {
        Drank dranken = new Drank
        { Naam = "Soep", Prijs = 1.90M };
        lblDrankje.Content = dranken.ToString();
        GroupBox1.IsEnabled = false;
    }

1 个答案:

答案 0 :(得分:1)

您可以使用所有点击事件的逻辑创建方法

private void DrankClick(string naam, decimal prijs)
{
    Drank dranken = new Drank
    { Naam = naam, Prijs = prijs };
    lblDrankje.Content = dranken.ToString();
    GroupBox1.IsEnabled = false;
}

然后为每个事件设置一个方法,例如

private void btnCola_Click(object sender, RoutedEventArgs e)
{
    DrankClick("Cola", 1.50M);
}