如何在WPF中使用可视化或逻辑树获取自定义控件Grid属性?

时间:2018-07-19 08:43:10

标签: c# wpf c#-4.0 wpf-controls custom-controls

感谢您阅读此问题,我真的对这个问题感到困惑。假设我在此xaml代码下面。`

     <ControlTemplate TargetType="{x:Type Input:TR1212_DensityProfiler}">
                            <Grid x:Name="MyGrid">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="16"/>
                                    <RowDefinition/>
                                    <RowDefinition Height="1"/>
                                </Grid.RowDefinitions>

                                <TextBlock 
                                    Text="{TemplateBinding Label}" 
                                    HorizontalAlignment="Center" 
                                    VerticalAlignment=" top" 
                                    FontSize="12" 
                                    FontFamily="Calibri"/>
<Grid 
                            x:Name="DensityBars_Grid" 
                            Grid.Row="1"/>
    <ControlTemplate/>

现在,我想在单元测试中测试网格行数。此网格行已更新或在XYZ.cs file.test中进行测试,我创建了单独的帮助器类以从树中获取数据。(基本上,我希望行计数为“ MyGrid”。)下面是代码。

 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++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            T 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;
                }
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }

        return foundChild;
    }

方法称为:VisualTreeHelperExtensions.FindChild<DependencyObject>(parent, "DensityBars_Grid"); 我不确定为什么我总是空着。如果我错了,或者有其他方法可以在单元测试中获得自定义控件网格行,请有人纠正我。

0 个答案:

没有答案