列表中的负指数<uicontrol>?</uicontrol>

时间:2011-04-04 05:44:32

标签: c# wpf arrays list indexing

我有一个List,一个单击事件来添加按钮,以及为显示消息而创建的每个按钮的单击事件。

public partial class MainWindow : Window
{
    List<Button> btnList = new List<Button>();

    public MainWindow()
    {
       InitializeComponent();
    }

    private void createbtn1_Click(object sender, RoutedEventArgs e)
    {
       Button btn = new Button();

       // wp is a WrapPanel in the MainWindow
       wp.Children.Add(btn);

       btn.Content = "Hello";
       btn.Click += hello_btn_Click;
       btnList.Add(btn);
    }

    private void hello_btn_Click(object sender, RoutedEventArgs e)
    {
       Button b = sender as Button;
       var bIndex = btnList.IndexOf(b);
       MessageBox.Show(bIndex.ToString());  
    }
}

现在编辑代码并运行正常。

1 个答案:

答案 0 :(得分:2)

我认为你有2个列表(btnLinkbtnList),并且让他们感到困惑:

btnLink.Add(btn);
...
var bIndex = btnList.IndexOf(b);