Get object by its Uid in WPF

jose picture jose · Dec 11, 2009 · Viewed 12.1k times · Source

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

Answer

Matt Hamilton picture Matt Hamilton · Dec 14, 2009

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");