O Jean
O Jean

Reputation: 105

How to find WPF expander children programmatically?

Heading

I have programmatically added an Expander, Grid, and some other Controls. Now I want to get the StackPanels Children which is in the Grid of Expanders Content.

Expander
  Grid
    StackPanel
      TextBox

How I can access to TextBox.Text ?

For StackPanel i would use

List<StackPanel = mypanel.Children.OfType<StackPanel>.ToList();

Super easy. But i can't access to Expander Content in that way.

List<Grid> = expander.Content.OfType<Grid>.ToList(); 

doesn't work.

Thanks to mm8 i fixed my problem as follows:

Grid grid = editable_expander.Content as Grid;
                List<StackPanel> stackpanel = grid.Children.OfType<StackPanel>().ToList();
                for(int i = 1; i < 2; i++)
                {
                    StackPanel sp = stackpanel[i];
                    List<TextBox> textbox = sp.Children.OfType<TextBox>().ToList();
                    for(int j = 0; j < textbox.Count; j++)
                    {
                        TextBox tb1 = textbox[j];
                        length = Convert.ToInt32(tb1.Text);
                    }
                }

Upvotes: 2

Views: 1018

Answers (2)

Dmitri Veselov
Dmitri Veselov

Reputation: 447

try

Grid gr;
StackPanel sp;
TextBox tb;
...
gr = ex.Content as Grid;
sp = gr.Children[0] as StackPanel;
tb = sp.Children[0] as TextBlock;
//reversed 
...
sp = tb.Parent as StackPanel;
gr = sp.Parent as Grid;
ex = gr.Parent as Expander;

Upvotes: 0

mm8
mm8

Reputation: 169200

Cast the Content property:

Grid grid = expander.Content as Grid;

Upvotes: 2

Related Questions