【问题标题】:How to create click event for dynamically created user controls in C#?如何在 C# 中为动态创建的用户控件创建点击事件?
【发布时间】:2015-09-06 16:46:33
【问题描述】:

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

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

【问题讨论】:

  • 你在使用数据模板吗?
  • 不,我没有使用 DataTemplate。

标签: c# windows events user-controls universal


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-31
      • 2021-08-19
      • 2017-07-05
      • 2014-03-06
      • 2014-01-26
      • 2014-05-23
      • 1970-01-01
      • 2017-07-22
      • 2019-05-13
      相关资源
      最近更新 更多