如何在ItemsControl中从ItemTemplate获取控件



我的视图有一个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;

您需要进一步深入可视化树来查找控件

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

最新更新