Как найти элемент в визуальном дереве? WP7 - PullRequest
3 голосов
/ 12 августа 2011

Как мне найти элемент, содержащийся в App.xaml, сетке с именем "audioPanel"?Я пытался:

Grid found = this.FindChild<Grid>(^*I can't find anything suitable*^, "audioPanel");

Как найти элементы управления WPF по имени или типу?

UPD: App.xaml http://pastebin.com/KfWbjMV8

Ответы [ 3 ]

2 голосов
/ 12 августа 2011

ОБНОВЛЕНИЕ: Вам нужно сочетание моего ответа и ответа HB.Используйте приведенную ниже версию FindChild и измените свой вызов на FindChild так, чтобы он выглядел как

var grid = FindChild<Grid>(Application.Current.RootVisual, "audioPanel");

Поскольку вы стилизуете фрейм телефонного приложения, вполне вероятно, что «элемент управления, к которому он применяется» из комментария HBбыть RootVisual (могут быть исключения из этого, я не уверен).

Также я предполагаю, что части "..." вашего App.xaml в pastebin где-то содержат ContentPresenter, иначе я не думаю, что ваш стиль будет работать.

END UPDATE

Если вы используете принятый ответ в вопросе, на который вы ссылаетесь ( WPF-способы поиска элементов управления ), и ваша сетка 'audioPanel' вложена внутрьдругой сетки, тогда вы все равно не найдете ее - в этом коде есть ошибка.Вот обновленная версия, которая будет работать, даже если элемент управления является вложенным:

    public static T FindChild<T>(DependencyObject parent, string childName)
        where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null)
        {
            return null;
        }

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            var childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<T>(child, childName);

                // If the child is found, break so we do not overwrite the found child. 
                if (foundChild != null)
                {
                    break;
                }
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name
                    foundChild = (T) child;
                    break;
                }

                // Need this in case the element we want is nested
                // in another element of the same type
                foundChild = FindChild<T>(child, childName);
            }
            else
            {
                // child element found.
                foundChild = (T) child;
                break;
            }
        }

        return foundChild;
    }
}
1 голос
/ 12 августа 2011

Если он находится в App.xaml, я бы предположил, что он является частью ресурса в Application.Resources, поскольку ресурсы, которые нигде не используются, не находятся в визуальном дереве, этого не будет.

Если это так, вы можете попытаться получить корень объекта из ресурсов и выполнить поиск по нему, например,

var root = Application.Current.Resources["MyKey"] as FrameworkElement;
Grid found = this.FindChild<Grid>(root, "audioPanel");
0 голосов
/ 05 марта 2014

только для полноты версии E. Z. Hart содержит ошибку, так как найденные дочерние дочерние элементы перезаписываются. вот рабочая версия

public static T FindChild<T>(this DependencyObject parent, string childName = null) where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (parent == null)
            return null;

        T foundChild = null;

        var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (var i = 0; foundChild == null && i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);                

            // If the child is not of the request child type child
            var childType = child as T;
            if (childType == null)
            {                   
                // recursively drill down the tree
                foundChild = FindChild<T>(child, childName);                    
            }
            else if (!string.IsNullOrEmpty(childName))
            {
                var frameworkElement = child as FrameworkElement;
                // If the child's name is set for search
                if (frameworkElement != null && frameworkElement.Name == childName)
                {
                    // if the child's name is of the request name
                    foundChild = (T)child;                        
                }
                else
                {
                    // Need this in case the element we want is nested
                    // in another element of the same type
                    foundChild = FindChild<T>(child, childName);
                }                    
            }
            else
            {
                // child element found.
                foundChild = (T)child;                    
            }
        }

        return foundChild;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...