簡體   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