I have an control in WPF which has an unique Uid. How can I retrive the object by its Uid?
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");
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With