我有一个按钮,每次单击时都会将此 StackPanel 添加到列表框。里面有一个按钮。我正在尝试弄清楚如何将代码添加到它正在添加的这个按钮中。理想情况下,我希望该按钮是删除按钮,因此它将删除列表中的该元素(本身)。我只是想弄清楚如何向我动态创建的按钮添加功能。希望这是有道理的
感谢您的帮助!
private void Button_Click_1(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
CheckBox checkBox = new CheckBox();
checkBox.IsChecked = true;
TextBox textBox = new TextBox();
textBox.Width = 100;
textBox.Text = textBox1.Text;
Button button = new Button(); //HOW DO I ADD CODE TO THIS BUTTON?
stackPanel.Children.Add(checkBox);
stackPanel.Children.Add(textBox);
stackPanel.Children.Add(button); //HOW DO I ADD CODE TO THIS BUTTON?
listBox1.Items.Add(stackPanel);
}
最佳答案
您可以通过编程方式向按钮添加点击处理程序,如下所示:
Button button = new Button(); //HOW DO I ADD CODE TO THIS BUTTON?
button.Click += btn_Click;
stackPanel.Children.Add(checkBox);
stackPanel.Children.Add(textBox);
stackPanel.Children.Add(button); //HOW DO I ADD CODE TO THIS BUTTON?
然后您需要点击事件处理程序
void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
// your code to execute when the button is clicked.
stackPanel.Items.Remove(button);
}
关于c# - WPF/C# - 向列表框中动态创建的按钮添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998445/