views:

343

answers:

1

Hello,

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

Thanks in advance

Jose

+3  A: 

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