Can't see controls inside User Control in VisualTreeHelper
I have a UserControl in wpf 4.0 that contains buttons, labels, text boxes, etc ... I want to loop these controls and when I get the buffer I want to take its name and store it in my list. Basically, all I want to do is create a Names_list from all my buttons in the UserControl.
I have a method that iterates through all the controls, and if it finds a button, this saves the name -
public void EnumVisual(Visual myVisual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
Button _button = childVisual as Button;
if (_button != null)
{
Class_Button _newButtonClass = new Class_Button();
if (_button.Name != null)
{
_newButtonClass.ButtonName = _button.Name;
}
ButtonsList.Add(_newButtonClass);
}
// Enumerate children of the child visual object.
EnumVisual(childVisual);
}
}
I always get an empty list. When I step into the code, debugging it and I look at the VisualTree of my UserControl, I can see all the panels and group boxes and grids, but I can’t see the buttons, labels and text boxes, even though each control has ax: Name and every control : x: FieldModifier = "public". This is very strange .... And I cannot figure out the reason for this, nor how to fix this problem ... can anyone tell me what I am doing wrong? thank
source to share
As @GazTheDestroyer suggested, you want to make sure the control pattern has been applied before trying to use the VisualTreeHelper. Try:
public void EnumVisual(Visual myVisual)
{
if(myVisual is FrameworkElement)
((FrameworkElement)myVisual).ApplyTemplate();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
Button _button = childVisual as Button;
if (_button != null)
{
Class_Button _newButtonClass = new Class_Button();
if (_button.Name != null)
{
_newButtonClass.ButtonName = _button.Name;
}
ButtonsList.Add(_newButtonClass);
}
// Enumerate children of the child visual object.
EnumVisual(childVisual);
}
}
source to share
You can use a tool like Snoop or WPF Inspector to inspect your control's visual tree. If these tools can do this, the error must be somewhere in your code, right?
source to share