如何处理n个UserControls的事件

时间:2019-04-15 14:13:30

标签: c# .net wpf

我想从数据库中获取一些数据,并用UserControls显示它们。这是我要处理的代码:

for (int i = 0; i < 20; i++)
{
    uc[i] = new UCMovieItem();
    uc[i].HorizontalAlignment = HorizontalAlignment.Right;
    uc[i].VerticalAlignment = VerticalAlignment.Top;
    uc[i].Margin = new Thickness(0, 10, 10, 0);
    uc[i].Cursor = Cursors.Hand;
    mainWrapPanel.Children.Add(uc[i]);
}
  • UCMovieItemUserControl

现在,我需要做的是,当用户单击其中任何一个UserControls时,我想检测单击了哪个按钮以显示一条消息,其中显示了已创建的UserControl的数量。 / p>

例如::如果用户点击了us[5],我想处理包含以下代码的事件:

MessageBox.Show(i);

现在我有一些问题:

  1. 如何处理for语句中每个USerControl的事件?
  2. 如何检测用户单击了哪个UserControl?
  3. 如何将i变量传递给clicked空隙以显示为消息?

2 个答案:

答案 0 :(得分:0)

假设您不知道命令,但是需要在代码中添加click事件处理程序,如下所示:

uc[i] = new UCMovieItem();
uc[i].HorizontalAlignment = HorizontalAlignment.Right;
uc[i].VerticalAlignment = VerticalAlignment.Top;
uc[i].Margin = new Thickness(0, 10, 10, 0);
uc[i].Cursor = Cursors.Hand;Button btn1 = new Button();
uc[i].Click += btn_Click;


//separate method
private void btn_Click(object sender, RoutedEventArgs e)
{
   int index = 0;
   for (int i = 0; i < uc.Length; i++) // determine which index the button has in a loop
   {
        if ((sender as Button) == uc[i])
        {
            index = i;
            MessageBox.Show(i);
        }
   }
   //do your stuff here

}

答案 1 :(得分:0)

您可以尝试使用 lambda ,例如

for (int i = 0; i < 20; i++)
{
    uc[i] = new UCMovieItem();
    ...
    mainWrapPanel.Children.Add(uc[i]);

    // little trick: we don't want to pass "i" to Clicked 
    // which will be "20" after the loop completed
    // but its local copy which will be 0..19 
    int number = i;

    // event handler as lambda
    uc[i].Clicked += (o, e) => {
      // Control itself will be passed explicitly
      UCMovieItem controlClicked = (o as UCMovieItem); 

      MessageBox.Show(number.ToString()); 
    }  
}