gpt4 book ai didi

c# - WPF/C# - 向列表框中动态创建的按钮添加功能

转载 作者:行者123 更新时间:2023-11-30 20:54:36 24 4
gpt4 key购买 nike

我有一个按钮,每次单击它时都会将此 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com