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

How to get control from ItemTemplate in ItemsControl?

我的视图有一组 UserControl(在 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 - 为用户控件添加了一个名称:

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

代码隐藏 - 直接查找 UserControl(没有按照答案的建议求助于 VisualTreeHelper):

                if (container == null)
                    continue;

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

您需要深入了解可视化树才能找到您的控件

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.

}

你可以在这里使用这个答案来制作一个遍历树的辅助方法: