我在xaml中定义了一个名字为morepictureWrapPan为WrapPanel,然后将控件添加在此WrapPanel中。由于要实现控件的删除功能,所以增加的textbox和button的名字都是有规律的
int textboxcount = 0; private void DynameAddBTN() { TextBox tb = new TextBox(); string countstr = "d" + textboxcount; tb.Name = "uploa" + countstr + "TB"; tb.IsEnabled = false; Button btn = new Button(); btn.Name = "uploa" + countstr + "BTN"; btn.Content = "Upload"; btn.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFD2E0EF")); //btn.Style = Resources["NormalBTNStyle"] as Style; //上传图片到服务器按钮的点击事件 btn.Click += UploadPictureDynamic; Button btn2 = new Button(); btn2.Name = countstr; btn2.Content = "x"; btn2.Background = null; btn2.Margin = new Thickness(0, 0, 9, 0); btn2.Click += closepic_Click; morepictureWrapPan.Children.Add(tb); morepictureWrapPan.RegisterName("uploa" + countstr + "TB",tb); morepictureWrapPan.Children.Add(btn); morepictureWrapPan.RegisterName("uploa" + countstr + "BTN", btn); morepictureWrapPan.Children.Add(btn2); textboxcount++; }
删除动态控件的功能实现
//动态删除控件 private void closepic_Click(object sender, RoutedEventArgs e) {
Button btn = sender as Button; Button closebtn = FindName("uploa" + btn.Name + "BTN") as Button; TextBox closetb = FindName("uploa" + btn.Name + "TB") as TextBox; //移除子节点的textbox、button morepictureWrapPan.Children.Remove(closebtn); morepictureWrapPan.Children.Remove(closetb); morepictureWrapPan.Children.Remove(btn); }