压缩大量的按钮点击事件

Condensing lots of Button Click Events

我有 40 个按钮,它们在单击时都略有不同,如果可以的话,我想将其压缩。我还想说,如果单击其中一个按钮,请创建一个可以通过 class.

访问的时间戳

这是 40 个按钮中的 2 个按钮的代码:

private void Btn1_Click(object sender, RoutedEventArgs e)
{
   for (int i = 1; i < 5; i++)
   {
       CheckBox CheckBox = (this.FindName(string.Format("Check{0}", i)) as CheckBox);

       if (CheckBox != null)
       {
          CheckBox.IsChecked = true;
       }
    }
}

private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
  for (int i = 1; i < 5; i++)
  {
    CheckBox CheckBox1 = (this.FindName(string.Format("Check_D{0}", i)) as CheckBox);

    if (CheckBox1 != null)
    {
       CheckBox1.IsChecked = false;
    }
  }
}

我认为一种方法是将它放在一个数组中,每当单击 40 个按钮中的一个时,它就会在数组中查找下一步要做什么?我不太确定,谢谢!

您可以使用一种方法使这变得简单。

答案根据 this 讨论更新

private void DoWork(int checkboxGroup, bool enable)
{
    int start = checkboxGroup * 4;
    for (int i = start; i < start + 4; i++)
    {
        CheckBox CheckBox = this.FindName("CheckBox" + i) as CheckBox;

        if (CheckBox != null)
        {
            CheckBox.IsChecked = enable;
        }
    }
}

private void Btn1_Click(object sender, RoutedEventArgs e)
{
    DoWork(1 , true);
}
private void BtnDisable1_Click(object sender, RoutedEventArgs e)
{
    DoWork(1 , false);
}

因为有 40 个这样的方法,所以您可以使用表达式主体方法。您必须拥有 C#6 才能使用此功能。

private void Btn1_Click(object sender, RoutedEventArgs e) => DoWork(1 , true);
private void BtnDisable1_Click(object sender, RoutedEventArgs e) => DoWork(1 , false);

private void Btn2_Click(object sender, RoutedEventArgs e) => DoWork(2, true);
private void BtnDisable2_Click(object sender, RoutedEventArgs e) => DoWork(2, false);

// and so on