如何从ItemsControl中的ItemTemplate获取控件?

时间:2015-08-04 13:40:17

标签: wpf xaml itemscontrol itemtemplate itemcontainergenerator

My View有一个UserControls集合(在ItemsControl的ItemTemplate中定义),我希望得到对它们的引用。

我正在使用ItemContainerGenerator.ContainerFromIndex,但它正在返回ContentPresenter,而我需要获取我的UserControl类型PlotterColetaCanalUnico。我该怎么做?

的Xaml:

        <ItemsControl x:Name="plotter" ItemsSource="{Binding Sinais}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="1" IsItemsHost="True"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border x:Name="upper_light_border" BorderThickness="1,0,0,0" BorderBrush="#FFE5E5E5" SnapsToDevicePixels="True">
                        <Border x:Name="lower_dark_border" BorderThickness="0,0,0,1" BorderBrush="#FF1A1A1A" SnapsToDevicePixels="True">
                            <local:PlotterColetaCanalUnico/>
                        </Border>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

代码背后:

    IEnumerable<PlotterColetaCanalUnico> SubPlotters 
    {
        get
        {
            var plotters = new List<PlotterColetaCanalUnico>();

            for(int i = 0; i < plotter.Items.Count; i++)
            {
                var container = (UIElement)plotter
                                 .ItemContainerGenerator
                                 .ContainerFromIndex(i);

                // "container" ends up being ContentPresenter,
                // so the following cast does not work!
                var subPlotter = container as PlotterColetaCanalUnico;

                if (subPlotter != null)
                {
                    plotters.Add(subPlotter);
                }
            }

            return plotters;
        }
    }

我根据接受的答案开始工作,并进行了以下更改:

Xaml - 为UserControl添加了一个名称:

<local:PlotterColetaCanalUnico x:Name="plotterCanal"/>

代码隐藏 - 直接查找UserControl(不按答案建议使用VisualTreeHelper):

                if (container == null)
                    continue;

                var template = container.ContentTemplate;
                var subPlotter = template.FindName("plotterCanal", container) as PlotterColetaCanalÚnico;

1 个答案:

答案 0 :(得分:1)

您需要深入挖掘视觉树以找到您的控件

if (container != null)
{
    var template = container.ContentTemplate;
    var border = template.FindName("upper_light_border", container) as Border;
    // From here, use VisualTreeHelper.GetChild to dig down in to the visual tree and find your control.

}

您可以在此处使用此答案来制作遍历树的辅助方法:https://stackoverflow.com/a/1759923/1231132