通过 WPF 中的 Uid 获取对象 [英] Get object by its Uid in WPF

查看:25
本文介绍了通过 WPF 中的 Uid 获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 中有一个具有唯一 Uid 的控件.如何通过 Uid 检索对象?

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

这篇关于通过 WPF 中的 Uid 获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆