如何在c#中为动态创建的用户控件创建点击事件

本文关键字:创建 用户 控件 事件 动态 | 更新日期: 2023-09-27 18:11:07

我正在创建一个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);
            }
        }
    }

那么我如何创建一个事件,当用户控件被按下时触发?

如何在c#中为动态创建的用户控件创建点击事件

当您创建控件时,您所需要做的只是将控件链接到一个新事件:

// 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...
}

我得到了它的工作,即使项目与不同的文本等。我将根据一个按钮被添加到面板来解释它。您需要一个List<>来存储项目,在本例中是按钮。

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

在这个例子中我也有一个Panel

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!'"";
    }