16

一意の Uid を持つ WPF のコントロールがあります。Uid でオブジェクトを取得するにはどうすればよいですか?

4

4 に答える 4

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

次に、次のように呼び出すことができます。

var el = FindUid("someUid");
于 2009-12-14T04:18:37.370 に答える
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;
}
于 2012-12-10T11:07:46.530 に答える
2

これの方が良い。

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;
}
于 2012-07-24T18:59:32.883 に答える