Get object by its Uid in WPF

2019-01-27 13:46发布

问题:

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

回答1:

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


回答2:

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;
}


回答3:

This is better.

public static UIElement FindUid(this DependencyObject parent, string uid) {
    int count = VisualTreeHelper.GetChildrenCount(parent);

    for (int i = 0; i < count; i++) {
        UIElement el = VisualTreeHelper.GetChild(parent, i) as UIElement;
        if (el != null) {
            if (el.Uid == uid) { return el; }
            el = el.FindUid(uid);
        }
    }
        return null;
}


回答4:

An issue I had with the top answer is that it won't look inside content controls (such as user controls) for elements within their content. In order to search inside these I extended the function to look at the Content property of compatible controls.

public static UIElement FindUid(this DependencyObject parent, string uid)
{
    var count = VisualTreeHelper.GetChildrenCount(parent);

    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;
    }

    if (parent is ContentControl)
    {
        UIElement content = (parent as ContentControl).Content as UIElement;
        if (content != null)
        {
            if (content.Uid == uid) return content;

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