[英]WPF / C# - Adding functionality to a button dynamically created inside a listbox
我有一個按鈕,每次單擊時都會將此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);
}
那是最簡單的設置。 理想情況下,您需要更多錯誤處理等。
Button button = new Button();
button.Click += (s, args) => { listBox1.Items.Remove(stackPanel); };
嘗試這個。
添加具有文本塊和按鈕的Stackpanel
private void OnSaveClick(object sender, RoutedEventArgs e)
{
StackPanel stp = new StackPanel();
stp.Orientation = Orientation.Horizontal;
stp.Children.Add(new TextBlock()
{
Text = string.Format("Item {0}", lstitems.Items.Count),
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch
});
Button btn = new Button();
btn.Content = string.Format("Delete Item {0}", lstitems.Items.Count);
btn.Height = 25;
btn.Width = 100;
btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
btn.Click += btnDeleteClick;
stp.Children.Add(btn);
lstitems.Items.Add(stp);
}
刪除按鈕單擊處理程序
void btnDeleteClick(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
if (btn != null)
{
var st = FindParent<StackPanel> (btn); //stackpanel as we have added item as stackpanel.
if (st != null)
lstitems.Items.Remove(st);
}
}
在可視樹中找到對象的類型。
public T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.