Wednesday, September 09, 2009

How to get content and text of each element of a Window

 Some times it is needed to get the content/text of  the children of a control.Then we have to iterate through all elements and should know its type.After comparing its type with the predefined types, we can cast that UIElement object to the particular object type.Then we can get/set its text/content values.Here is the sample code.

        foreach (UIElement oObject in this.LayoutRoot.Children)
            {

                Type type= oObject.GetType();
                string name=oObject.GetValue(NameProperty).ToString();
                if (type == typeof(TextBlock))
                {
                    TextBlock textBlock = oObject as TextBlock;
                    if (textBlock != null)
                    {
                        MessageBox.Show(textBlock.Text);
                    }
                }

                if (type == typeof(TextBox))
                {

                    TextBox textBox = oObject as TextBox;
                    if(textBox != null)
                    {

                        MessageBox.Show(textBox.Text);
                    }
                }
                if(type == typeof(ComboBox))
                {
                    ComboBox comboBox = oObject as ComboBox;

                    if(comboBox != null)
                    {

                        MessageBox.Show(comboBox.SelectedItem.ToString());

                    }

                }

                if(type==typeof(Button))

                {

                    Button button = oObject as Button;

                    if(button != null)

                    {

                        MessageBox.Show(button.Content.ToString());

                    }
                }        
}

No comments: