遍历stackPanel.children [英] Loop through stackPanel.children genericaly

查看:203
本文介绍了遍历stackPanel.children的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中,我正在动态添加要循环浏览的控件(例如TextBox,ComboBox,Label等),并从用户输入数据的每个适用控件(例如非Labels)中获取值。



In code I am dynamically adding controls (e.g. TextBox, ComboBox, Label, etc) that I would like to now loop through and get the values from each applicable (e.g. not Labels) control that a user inputted data for.

        foreach (Control control in EditForm.Children)
        {
            values = new List<string>();
            fieldName = control.Name;

            if (control is ComboBox)
            {
                ComboBox cmb = control as ComboBox;

                string value = cmb.SelectedValue.ToString();
            }
         }

问题是我在运行时出错


无法将类型为 System.Windows.Controls.TextBlock的对象转换为类型为 System.Windows.Controls的

Unable to cast object of type 'System.Windows.Controls.TextBlock' to type 'System.Windows.Controls.Control'.

是否应该使用更通用的类代替 Control?我该如何遍历每个控件并访问所需的值(包括控件的名称)

Is there a more generic class I should be using instead of 'Control'? How can I loop through each control and have access to the needed values (includes the control's Name)

推荐答案

UIElement最多可能是一个安全的选择。

"UIElement" is most likely a safe choice.

如果您只对特定类型的元素感兴趣,还可以考虑使用Linq按类类型过滤元素(别忘了包括使用System.Linq指令):

If you're only interested elements of a specific type, you can also consider using Linq to filter out elements by class type (don't forget to include a "using System.Linq" directive):

foreach (ComboBox combo in EditForm.Children.OfType<ComboBox>())
{
   //...
}

这篇关于遍历stackPanel.children的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆