0

I would like to find all of the controls within a WPF control specially in Datagrid, DataGridTemplateColumn. I have had a look at a lot of samples and it seems that they all either require a Name to be passed as parameter or simply do not work.

prparikh
  • 31
  • 3
  • 8

1 Answers1

0

What have you tried that "require a name to be passed or simply don't work" and what's wrong with the former?

private void FindAllChildren()
{
    var depObj = dataGrid;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
        if (child is DataGridTemplateColumn)
        {
            // do a thing
        }
    }
}

Adapted from here: https://stackoverflow.com/a/978352/1189566

Community
  • 1
  • 1
sab669
  • 3,984
  • 8
  • 38
  • 75
  • I tried that way but it gets me null value every time. also I tried something like object item = dgTest.FindName("testTemp"). But item always be null – prparikh Nov 18 '15 at 20:21
  • 2
    Are you running it after the Loaded Event? Otherwise, you'll always get null. – DeathTails Nov 18 '15 at 20:24
  • @prparikh Well you're doing something wrong, because now that I'm looking deeper into it this is almost identical to MSDN's example: https://msdn.microsoft.com/en-us/library/system.windows.media.visualtreehelper.getchild(v=vs.110).aspx – sab669 Nov 18 '15 at 20:27
  • @DeathTrails: it is after button click event. – prparikh Nov 18 '15 at 20:33
  • Are you using it like: `var list = FindVisualChildren(myDataGridColumn);`? This function works perfectly fine for me. That should get all the UIElements in the DataGridTemplateColumn. Recursively, that is. You may want to take out the recursive call if you only want a single level. – DeathTails Nov 18 '15 at 20:43
  • I'm trying to access datagrid inside RowDetailsTemplate so it is something like . But when I use VisualTreeHelper.GetChildrenCount(myDataGrid), it returns 1. – prparikh Nov 19 '15 at 13:18