通过WPF中的Uid获取对象

jos*_*ose 16 wpf object wpf-controls fetch

我在WPF中有一个控件,它有一个独特的Uid.我怎样才能通过其Uid来回溯对象?

Mat*_*ton 12

你几乎必须通过蛮力来做.这是您可以使用的辅助扩展方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

var el = FindUid("someUid");
Run Code Online (Sandbox Code Playgroud)


pr0*_*g3r 5

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;
}
Run Code Online (Sandbox Code Playgroud)