silverlight - 在 Silverlight 中查找所有 TextBox 控件的通用方法

标签 silverlight

我在一个页面上有几个 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/

相关文章:

c# - MediaElement 自动播放 = "False"错误

javascript - 如何通过 javascript 从 silverlight 媒体播放器 (player.xap) 获取播放状态?

wpf - 在WPF/Silverlight中使用HierarchicalDataTemplate的类似于文件系统的TreeView

silverlight - 使用外部控件自定义 Silverlight Dataform 的命令

c# - 哪种物理引擎适合 Silverlight 池引擎?

Silverlight OOTB 支持 'Save File' 浏览器对话框

silverlight - 一个不错的 Silverlight 3.0 引用应用程序,有源码吗?

c# - 如何将 SelectedItem(从 ListBox)绑定(bind)到变量?

c# - 如何将附加本地对象变量传递给我的事件处理程序?

c# - 调度程序如何工作线程?