简体   繁体   English

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

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

I have added a GroupBox to my main Grid and am populating it dynamically with controls. 我已经在我的主网格中添加了一个GroupBox,并使用控件动态填充它。 I need to get a specific textbox within that GroupBox in an onClick event. 我需要在onClick事件中在该GroupBox中获取特定的文本框。 I am able to loop through the GroupBox and fine, like this... 我可以像这样循环遍历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;
      }
  }

... but if i just want to access a specific TextBox i keep coming back with a null value. ...但是如果我只想访问特定的TextBox,我会继续返回null值。 here is how i'm trying to get it... 这就是我想要的方式...

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

... where PropertyId_9 is the name of a textbox that i added dynamically to the GroupBox. ...其中PropertyId_9是我动态添加到GroupBox的文本框的名称。 Any idea how i get that textbox so i can get it's value? 知道我如何获取该文本框,以便获得价值吗?

Thanks! 谢谢!

You're using the wrong Linq method. 您使用了错误的Linq方法。 That code returns an IEnumerable of TextBoxes, not just the TextBox. 该代码返回一个IEnumerable的TextBoxes,而不仅仅是TextBox。 Use Single or SingleOrDefault instead of Where: 使用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