如何访问嵌套的 StackPanel

卡米尔·斯沃特温斯基

我正在使用交互式数据显示库,并且我想动态生成我的图表。不幸的是,我无法按名称访问其中一个 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())访问它时,它似乎不存在。

当然

在您的代码中实现这一点

  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 chartPanel= FindChildControl<StackPanel>(plotter, "chartPanel") as StackPanel;

现在您可以编辑您的 Stackpanel。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 XAML 中如何对齐嵌套的 StackPanel

WPF如何使StackPanel可滚动

如何设置StackPanel的IsEnabled属性

如何间隔StackPanel的子元素?

如何在代码中访问StackPanel的Canvas.Left属性?

如何在 StackPanel 上使用边框

如何在StackPanel或ListView中叠加项目?

如何为StackPanel儿童设置边距

如何在ScrollViewer中滚动水平StackPanel?

如何访问 ItemsControl->ItemTemplate->DataTemplate->StackPanel 中的按钮?wpf c#

如何将命令绑定到StackPanel或Grid Tap事件?

如何在Metro App中对齐StackPanel上的图像内容

如何在水平StackPanel内的ListView中显示组?

WPF StackPanel - 如何将项目从底部推出

如何使StackPanel的子级向下填充最大空间?

Windows Phone StackPanel子元素如何共享可用宽度

如何使Stackpanel调整大小以适合其堆叠的控件?

如何使用GAS在StackPanel中的面板之间更改焦点

如何在StackPanel中包装一组TextBlocks?

XAML-如何在StackPanel中彼此对齐控件

如何对父Stackpanel的ActualHeight进行数据绑定

如何在Xaml中制作可收缩的Stackpanel

如何使用ComboBox SelectionChanged事件更改StackPanel颜色?

如何在WPF中使用StackPanel从Listview获取值

如何为每个StackPanel项目设置单独的工具提示?

如何在UWP中将stackpanel添加到menuflyoutitem?

如何将StackPanel的背景设置为样式资源中定义的ImageBrush?

具有Stackpanel-Items的ListBox-如何启用滚动?WPF

Grid内部的StackPanel-如何将其元素放置在不同的列中