對於這個XAML上面我會做這樣的:
在每一個按鈕名稱的Click事件句柄「添加新的輸入行「,我的意思是你可以使用這個事件的所有按鈕。
private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
StackPanel stkButtonParent = btn.Parent as StackPanel;
StackPanel stkCover = stkButtonParent.Parent as StackPanel;
StackPanel newRow = NewRow();
stkCover.Children.Add(newRow);
}
private StackPanel NewRow() {
StackPanel stk = new StackPanel();
stk.Orientation = Orientation.Horizontal;
Label lbl = new Label();
lbl.Foreground = Brushes.Red; // some attribute
TextBox txt = new TextBox();
txt.Background = Brushes.Transparent; // some attribute
Button btn = new Button();
btn.Content = "Add new row";
btn.Click += btn_Click;
stk.Children.Add(lbl);
stk.Children.Add(txt);
stk.Children.Add(btn);
return stk;
}
是的。例如,使用'ItemsPanel',將其綁定到'ObservableCollection',使用'StackPanel'作爲內容或模板,並將按鈕的onclick事件處理程序中的項目添加到集合中。 – Jensen