如何访问嵌套的StackPanel

时间:2018-05-14 09:36:31

标签: c# wpf

我正在使用交互式数据显示库,我想动态生成我的图表。不幸的是,我无法通过其名称访问其中一个StackPanel:

<Grid>
    <d3:Chart Name="plotter">
        <d3:Chart.Title>
            <TextBlock HorizontalAlignment="Center" FontSize="18" Margin="0,5,0,5">Line graph legend sample</TextBlock>
        </d3:Chart.Title>
        <d3:Chart.LegendContent>
            <d3:LegendItemsPanel>
                <d3:LegendItemsPanel.Resources>
                    <DataTemplate x:Key="InteractiveDataDisplay.WPF.LineGraph">
                        <StackPanel Name="chartPanel" Orientation="Horizontal"> 
                        </StackPanel>
                    </DataTemplate>
                </d3:LegendItemsPanel.Resources>
            </d3:LegendItemsPanel>
        </d3:Chart.LegendContent>
        <Grid Name="lines"/>
    </d3:Chart>
</Grid>

当我试图通过名称(chartPanel.method())访问它时,它似乎不存在。

1 个答案:

答案 0 :(得分:0)

在您的代码中实现此功能

  private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
    {
        int childNumber = VisualTreeHelper.GetChildrenCount(control);
        for (int i = 0; i < childNumber; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(control, i);
            FrameworkElement fe = child as FrameworkElement;
            // Not a framework element or is null
            if (fe == null) return null;

            if (child is T && fe.Name == ctrlName)
            {
                // Found the control so return
                return child;
            }
            else
            {
                // Not found it - search children
                DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
                if (nextLevel != null)
                    return nextLevel;
            }
        }
        return null;

之后你可以使用这个方法搜索stackpanel:

 StackPanel chartPanel= FindChildControl<StackPanel>(plotter, "chartPanel") as StackPanel;

现在您可以编辑Stackpanel。