Loop through stackPanel.children genericaly

感情迁移 提交于 2019-12-11 04:44:34

问题


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();
            }
         }

The problem is that I get an error during runtime of

Unable to cast object of type 'System.Windows.Controls.TextBlock' to type 'System.Windows.Controls.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)


回答1:


"UIElement" is most likely a safe choice.

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>())
{
   //...
}


来源:https://stackoverflow.com/questions/14688136/loop-through-stackpanel-children-genericaly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!