我在一个页面上有几个 Silverlight 控件,并希望查询所有 TextBox 类型的控件并使其正常工作。
现在,我正在处理的 Silverlight 表单可以添加更多 TextBox 控件。因此,当我测试 TextBox 控件是否具有值时,我可以这样做:
if (this.TextBox.Control.value.Text() != String.Empty)
{
// do whatever
}
但我宁愿灵活地在任何 Silverlight 表单上使用它,而不管我拥有的 TextBox 控件的数量。
关于我将如何去做的任何想法?
最佳答案
听起来您需要像下面的 GetTextBoxes 这样的递归例程:
void Page_Loaded(object sender, RoutedEventArgs e)
{
// Instantiate a list of TextBoxes
List<TextBox> textBoxList = new List<TextBox>();
// Call GetTextBoxes function, passing in the root element,
// and the empty list of textboxes (LayoutRoot in this example)
GetTextBoxes(this.LayoutRoot, textBoxList);
// Now textBoxList contains a list of all the text boxes on your page.
// Find all the non empty textboxes, and put them into a list.
var nonEmptyTextBoxList = textBoxList.Where(txt => txt.Text != string.Empty).ToList();
// Do something with each non empty textbox.
nonEmptyTextBoxList.ForEach(txt => Debug.WriteLine(txt.Text));
}
private void GetTextBoxes(UIElement uiElement, List<TextBox> textBoxList)
{
TextBox textBox = uiElement as TextBox;
if (textBox != null)
{
// If the UIElement is a Textbox, add it to the list.
textBoxList.Add(textBox);
}
else
{
Panel panel = uiElement as Panel;
if (panel != null)
{
// If the UIElement is a panel, then loop through it's children
foreach (UIElement child in panel.Children)
{
GetTextBoxes(child, textBoxList);
}
}
}
}
实例化一个空的 TextBox 列表。调用 GetTextBoxes,传入页面上的根控件(在我的例子中,就是 this.LayoutRoot),GetTextBoxes 应该递归地遍历作为该控件后代的每个 UI 元素,测试它是否是一个 TextBox(添加它到列表),或者一个面板,它可能有它自己的后代来递归。
希望有帮助。 :)
关于silverlight - 在 Silverlight 中查找所有 TextBox 控件的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604144/