1

Sorry for a potentially dumb question, I am still new at this. I really appreciate your help. Referring to Get a Windows Forms control by name in C# But I don't have a "this.Controls" available. Is there something I am missing here?

In other words, when I type "this." and visual studio populates a list of option, there is no "Controls" option.

Community
  • 1
  • 1
Adam S
  • 8,665
  • 17
  • 63
  • 98

4 Answers4

4

In WPF, you should try this.FindName(string name)

Button b = (Button)this.FindName("button1");
Anthony Pegram
  • 119,149
  • 26
  • 217
  • 245
1

The link you gave was for Winforms, you are looking for a WPF way to do it which is different.

Brian R. Bondy
  • 327,498
  • 120
  • 583
  • 623
1

If you are looking to iterate through the controls for whatever reason, in your Window class, you can iterate through the LayoutRoot's children (e.g.)

    foreach (object o in this.LayoutRoot.Children)
    {
        MessageBox.Show(o.GetType().Name);
    }

Keep in mind that the children can also contain children, so you'll need to delve into each of those as needed.

Robaticus
  • 22,427
  • 5
  • 53
  • 63
0

I have to add whats LayoutRoot: because I am new in WPF I did not know whats that

After general research I found them: it's your Grid if you write grid visual studio did not find them what you should do?

go to your window next go to the Grid Start tag : <grid> next add : x:Name="your desired name"

like this : <Grid x:Name="FRM">

now go back to code yourwindow.xaml.cs

not you see it works foreach (object o in this.FRM.Children)

I hope it was useful for a novice like me

Dharman
  • 26,923
  • 21
  • 73
  • 125