如何查看ItemControl.项目面板.来自代码隐藏的模板

本文关键字:代码 隐藏 ItemControl 项目 何查看 | 更新日期: 2023-09-27 17:51:00

我有这个xaml样本:

<ItemsControl MinHeight="150" ItemsSource="{Binding fieldList}" Name="myItemsControl">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas Name="canvasFields" MinHeight="150" Background="White" Margin="10" Height="{Binding HauteurCanvas}"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="Canvas.Left"
                            Value="{Binding Column}" />
                        <Setter Property="Canvas.Top"
                            Value="{Binding Row}" />
                        <Setter Property="Width"
                            Value="{Binding Width}" />
                        <Setter Property="Height"
                            Value="{Binding Height}" />
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                            <c:ControlCustomField MouseLeftButtonDown="ControlCustomField_MouseLeftButtonDown" MouseMove="ControlCustomField_MouseMove" MouseLeftButtonUp="ControlCustomField_MouseLeftButtonUp"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

我想从代码后面访问canvasFields,但我只能看到我的ItemsControl。

到目前为止,我尝试了很多东西。。在代码隐藏中,这些都不起作用:

canvasFields这是不可见的。

((Canvas)(myItemsControl.ItemsPanel.Template))这会出现"无法转换"错误。

myItemsControl.canvasFields这也看不到。


好吧,你看交易。。如何从代码后面"查看"canvasFields?

我可能错过了一些非常明显的东西来访问它…
提前感谢!

如何查看ItemControl.项目面板.来自代码隐藏的模板

您无法访问它!因为这是一个模板。而不是创建的控件。

您应该看看FrameworkElement.GetTemplateChild方法,它就是为了这个目的。但是,这需要对ItemsControl进行子类化,因为此方法受到保护。

如果需要避免这种情况,那么可以使用VisualTreeHelper.GetChild方法遍历ItemsControl的可视化树,分析元素的类型和Name属性,直到找到合适的元素。

您需要遍历ItemsControl的可视子体,并查找满足以下任一标准的Panel

if (panel.IsItemsHost && panel.TemplatedParent == itemsControl)
    /* You've found the ItemsPanel. */;
var itemsPresenter = panel.TemplatedParent as ItemsPresenter;
if (itemsPresenter != null && itemsPresenter.TemplatedParent == itemsControl)
    /* You've found the ItemsPanel. */;

它可能不是100%可靠的,但它还没有让我失望。