Reputation: 12486
In XAML I have created CustomWindow
. It contains many nested elements. Is exists simply method to get all named elements (I set names through x:Name="SomeName"
), marked as public (I set modifier through x:FieldModifier="public"
)?
Upvotes: 0
Views: 1240
Reputation: 4684
There is no out of the box way I'm aware of. You have to browse the VisualTree using the VisualTreeHelper
and check if they have the properties you are interrested in.
Here is a method that can do what you need :
public static IEnumerable<FrameworkElement> FindVisualChildren(FrameworkElement obj, Func<FrameworkElement, bool> predicate)
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var objChild = VisualTreeHelper.GetChild(obj, i);
if (objChild != null && predicate(objChild as FrameworkElement))
{
yield return objChild as FrameworkElement;
}
foreach (FrameworkElement childOfChild in FindVisualChildren(objChild as FrameworkElement, predicate))
{
yield return childOfChild;
}
}
}
}
Usage could be something like that for a check on the name only :
var children = FindVisualChildren((FrameworkElement)sender, o => !string.IsNullOrEmpty(o.Name));
Upvotes: 1