1

I have a project with various controls some with a name and some without. I want to loop though all controls and automatically set Tag=Name when present. I have seen various solution like this one:

WPF: How do I loop through the all controls in a window?

and this works but then I can't get to set :

foreach (Visual ctrl in MainGrid.GetChildren())
{
    ctrl.Tag = ctrl.Name;<------
}

To me the tag is used recognize the event es when pressing different buttons. Thanx Patrick

Community
  • 1
  • 1
Patrick
  • 3,073
  • 2
  • 22
  • 60

1 Answers1

4

Tag property only exists on FrameworkElements

So you need to make a cast :

foreach (Visual ctrl in MainGrid.GetChildren())
{
    FrameworkElement fxElt = ctrl as FrameworkElement;
    if( fxElt != null)
        fxElt.Tag = fxElt.Name;
}

Regards

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53
  • Thanx that works. You just forgot to change the last line. It's not fxElt.Tag = ctrl.Name; but fxElt.Tag = fxElt.Name; – Patrick Nov 13 '15 at 15:04