简体   繁体   English

如何删除在WPF网格中动态创建的文本框控件?

[英]How to Remove Textbox control created dynamically in WPF Grid?

I am unable to remove the textbox which is created Dynamically using Combobox selected Item in Grid. 我无法删除使用组合框在网格中选择的项目动态创建的文本框。 if the selected value is not equal to "Other (describe)", i have to remove the textbox. 如果所选值不等于“其他(描述)”,则必须删除文本框。 I have this code.. 我有这个代码。

private void btn_addnew_Click(object sender, RoutedEventArgs e)
    {
       ComboBox cmb=new ComboBox();
        .....
       cmb.SelectionChanged+= cmb_SelectionChanged;
       .....
    }


void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var txt = new TextBox();
        if (e.AddedItems[0].ToString() == "Other (describe)")
        {

            var row = (int)((ComboBox)sender).Tag;
            Grid.SetRow(txt, row);
            Grid.SetColumn(txt, 1);
            txt.Margin = new Thickness(10, 10, 0, 0);
            grid_typeFixture.Children.Add(txt);
        }
        else
           grid_typeFixture.Children.Remove(txt);
    }

如果不遵循命名规则,则存在动态设置文本框名称的风险(示例:文本框名称不能有空格),而是可以在创建文本框时使用“ Tag”属性,并在需要时搜索它去掉它。

Assign a name to your TextBox while creating, you can use RegisterName , 在创建时为您的TextBox分配一个名称,您可以使用RegisterName

        txt = new TextBox();
        txt.Margin = new Thickness(10, 10, 0, 0);
        txt.Name = "DynamicLine" + i;
        RegisterName(txt.Name, txt);
        Grid.SetRow(txt, i);
        Grid.SetColumn(txt, 2);
        grid_typeFixture.Children.Add(txt);

And you can remove like this, using FindName 您可以使用FindName这样删除

     txt = (TextBox)grid_typeFixture.FindName("lbl_DynamicLine" + row);
     if (txt != null)
            {
                UnregisterName(txt.Name); 
                grid_typeFixture.Children.Remove(txt);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM