繁体   English   中英

在C#WPF GroupBox中查找特定的动态TextBox

[英]Find a specific dynamic TextBox in a C# WPF GroupBox

我已经在我的主网格中添加了一个GroupBox,并使用控件动态填充它。 我需要在onClick事件中在该GroupBox中获取特定的文本框。 我可以像这样循环遍历GroupBox并...

  foreach (Control ctl in ((Grid)gpMccEngineProperties.Content).Children)
  {
      if (ctl.GetType() == typeof(TextBox))
      {
          TextBox textbox = (TextBox)ctl;
          PropertyValue propertyValue = new PropertyValue();
          propertyValue.Value = textbox.Text;
      }
  }

...但是如果我只想访问特定的TextBox,我会继续返回null值。 这就是我想要的方式...

TextBox txt = ((Grid)gpMccEngineProperties.Content).Children.OfType<TextBox>().Where(t => t.Name == "PropertyId_9") as TextBox;

...其中PropertyId_9是我动态添加到GroupBox的文本框的名称。 知道我如何获取该文本框,以便获得价值吗?

谢谢!

您使用了错误的Linq方法。 该代码返回一个IEnumerable的TextBoxes,而不仅仅是TextBox。 使用Single或SingleOrDefault代替Where:

TextBox txt = ((Grid)gpMccEngineProperties.Content).Children.OfType<TextBox>().Single(t => t.Name == "PropertyId_9");

暂无
暂无

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

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