如何在C#中为动态创建的用户控件创建click事件?

时间:2015-09-02 23:40:32

标签: c# windows events user-controls universal

我正在创建一个Windows通用应用程序,其中包含一个填充了用户控件的ListView。用户控件在运行时根据数据库中的元素动态添加到ListView。

public void ShowFavorites()
    {
        using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), (Application.Current as App).DBPath))
        {
            var Favorites = conn.Table<Favorites>();

            lvFavorites.Items.Clear();

            foreach (var fav in Favorites)
            {
                FavoriteItem favItem = new FavoriteItem();
                favItem.Favorite = fav;
                lvFavorites.Items.Add(favItem);
            }
        }
    }

那么如何创建一个在按下用户控件时触发的事件?

2 个答案:

答案 0 :(得分:0)

创建控件时,您只需将控件链接到新事件:

// Dynamically set the properties of the control
btn.Location = new Point((lbl.Width + cmb.Width + 17), 5);
btn.Size = new System.Drawing.Size(90, 23);
btn.Text = "Add to Table";

// Create the control
this.Controls.Add(btn);

// Link it to an Event
btn.Click += new EventHandler(btn_Click);

然后,当您(在这种情况下)点击新添加的按钮时,它将调用您的btn_Click方法:

private void btn_Click(object sender, EventArgs e)
{
    //do stuff...
}

答案 1 :(得分:0)

即使对于具有不同文本等的项目,我也能使用它。 我将根据添加到面板的按钮来解释它。 你需要一个List&lt;&gt;在其中存储项目,在本例中为按钮。

List<Button> BtList = new List<Button>();

在这种情况下我也有一个小组。

Panel PanelForButtons = new Panel();

这是我的代码,我希望它可以帮助你:

    void AddItemToPanel()
    {
        //Creating a new temporary item.
        Button TempBt = new Button();
        TempBt.Text = "Hello world!";

        //Adding the button to our itemlist.
        BtList.Add(TempBt);

        //Adding the event to our button.
        //Because the added item is always the last we use:
        PanelForButtons.Controls.Add(BtList.Last());
        BtList.Last().Click += MyButtonClicked;
    }

这是事件:

    void MyButtonClicked(object sender, EventArgs e)
    {
        //First we need to convert our object to a button.
        Button ClickedButton = sender as Button;

        //And there we have our item.
        //We can change the text for example:
        ClickedButton.Text = "The world says: \"Hello!\"";
    }
相关问题