我的视图有一组用户控件(在 ItemsControl 的 ItemTemplate 中定义),我想获得对它们的引用。
我正在使用ItemContainerGenerator.ContainerFromIndex
,但它正在返回ContentPresenter
,而我需要获取我的 UserControl 类型PlotterColetaCanalUnico
。我该怎么做?
xml:
<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;