0

How could I find a framework element in VisualTree by a predicate? Something like that :

public static FrameworkElement FindChild(FrameworkElement root, Predicate<> predicate)
{
   ...
}

I'm goint to use it something like that:

Button btn = FindChild(MainForm, element => element is Button);

Thanks for help in advance!

Alexander Knoth
  • 137
  • 1
  • 13
  • You should either call your method `FindSingleChild` or return an IEnumerable of FrameworkElements. After all, the predicate could be matched by more than one child. – Heinzi Jul 24 '12 at 09:33

3 Answers3

1

So the real question then is how to iterate throug all the children of the given "root" element. Because then you'll be able to call your predicate for that element and choose those you want. So I suppose you should distinguish here two different workflows - one - when the element is Panel, you should first pass it in, and then iterate over it's Children property and pass in every of those (both recursion and non-recursion will work, but you should go deeper into tree, and come back through levels in both cases). And in case of non panel element, just pass in that one to the predicate. Also you should think about the elements, which have "Content" property (I suppose this is defined in some base type, which I don't remember which one is), so check for the content element the same way. And that's all.

Regards, Artak

Artak
  • 2,819
  • 20
  • 31
1

You may use LINQ to find out the controls of particular type, maybe like this:

List<Button> btns = Controls.OfType<Button>().ToList();
Embedd_0913
  • 16,125
  • 37
  • 97
  • 135
0

Answers to this SO question describes many ways to look for controls in visual tree.

The predicate version is given there as link to this.

Community
  • 1
  • 1
Rafal
  • 12,391
  • 32
  • 54