2

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);
                    }
                }
Cœur
  • 37,241
  • 25
  • 195
  • 267
O Jean
  • 105
  • 9
  • 2
    Possible duplicate of [How to get children of a WPF container by type?](https://stackoverflow.com/questions/10279092/how-to-get-children-of-a-wpf-container-by-type) – Sinatr Sep 04 '17 at 10:06
  • @Sinatr doesn't work. – O Jean Sep 04 '17 at 10:11
  • 1
    Recursive solution lookup for children in visual tree from duplicate should give you a possibility to use either parent to find `TextBox` and then access its `Text` property. *"Doesn't work"* - can't do anything about it, sorry. – Sinatr Sep 04 '17 at 10:15

2 Answers2

2

Cast the Content property:

Grid grid = expander.Content as Grid;
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    That works for me thanks. Don't know which Person is disliking all answers here but thanks for your solution. Didnt thought to make it this way.. – O Jean Sep 04 '17 at 10:58
0

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;
Dmitri Veselov
  • 427
  • 6
  • 14