Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object by its Uid in WPF

I have an control in WPF which has an unique Uid. How can I retrive the object by its Uid?

like image 587
jose Avatar asked Dec 11 '09 12:12

jose


2 Answers

You pretty much have to do it by brute-force. Here's a helper extension method you can use:

private static UIElement FindUid(this DependencyObject parent, string uid)
{
    var count = VisualTreeHelper.GetChildrenCount(parent);
    if (count == 0) return null;

    for (int i = 0; i < count; i++)
    {
        var el = VisualTreeHelper.GetChild(parent, i) as UIElement;
        if (el == null) continue;

        if (el.Uid == uid) return el;

        el = el.FindUid(uid);
        if (el != null) return el;
    }
    return null;
}

Then you can call it like this:

var el = FindUid("someUid");
like image 92
Matt Hamilton Avatar answered Sep 19 '22 07:09

Matt Hamilton


public static UIElement GetByUid(DependencyObject rootElement, string uid)
{
    foreach (UIElement element in LogicalTreeHelper.GetChildren(rootElement).OfType<UIElement>())
    {
        if (element.Uid == uid)
            return element;
        UIElement resultChildren = GetByUid(element, uid);
        if (resultChildren != null)
            return resultChildren;
    }
    return null;
}
like image 29
pr0gg3r Avatar answered Sep 22 '22 07:09

pr0gg3r