Wpf – Get object by its Uid in WPF

fetch, object, wpf, wpf-controls

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

Best Solution

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