Как найти DataGrid с помощью VisualTreeHelper Generic Find? - PullRequest
0 голосов
/ 31 мая 2019

Общий static T FindChild(DependencyObject parent, string childName) не находит DataGrids.T childType = child as T; всегда возвращает null для DataGrids.

XAML:

<TabControl>
    <TabItem Header="TabItemHeader" FontSize="25">
        <DockPanel>
            <DataGrid Name="MyDataGrid">
            </DataGrid>
        </DockPanel>
    </TabItem>
</TabControl>

FindChild Call

DataGrid MyDataGrid;
MyDataGrid= FindChild<DataGrid>(ParentElement, "MyDataGrid");

FindChild

public static T FindChild<T>(DependencyObject parent, string childName)
        where T : DependencyObject {
            if (parent == null) return null;

            T foundChild = null;

            if (parent.GetType().ToString().Equals("System.Windows.Controls.TabControl")) {
                TabControl tabControl = parent as TabControl;
                for (int i = 0; i < tabControl.Items.Count; i++) {
                    TabItem tabItem = tabControl.Items[i] as TabItem;
                    DependencyObject dependencyObject = tabItem.Content as DependencyObject;
                    foundChild = FindChild<T>(dependencyObject, childName);

                    if(foundChild != null) {
                        break;
                    }
                }
            }
            else {
                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < childrenCount; i++) {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    T childType = child as T;
                    if (childType == null) {
                        foundChild = FindChild<T>(child, childName);
                        if (foundChild != null) break;
                    }
                    else if (!string.IsNullOrEmpty(childName)) {
                        if (VisualTreeHelper.GetChildrenCount(child) > 0) {
                            foundChild = FindChild<T>(child, childName);
                            if (foundChild != null) break;
                        }
                        var frameworkElement = child as FrameworkElement;
                        if (frameworkElement != null && frameworkElement.Name == childName) {
                            foundChild = (T)child;
                            break;
                        }
                    }
                    else {
                        foundChild = (T)child;
                        break;
                    }
                }
            }

            return foundChild;
        }

Если DataGrid заменен Grid, он работает отлично.И искал в соответствии с этим.

Ps: Если у кого-то есть лучшее решение для TabControl, я был бы признателен.

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