访问ListBoxItem的子级 [英] Accessing child of ListBoxItem

查看:92
本文介绍了访问ListBoxItem的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DataTemplate的ListBox,如下所示:

I have a ListBox with a DataTemplate that looks like this:

    <ListBox Name="listBox">
        <ListBox.ItemTemplate>
            <DataTemplate DataType="x:Type local:NumericIconDefinition">
                <Grid>
                    <ComboBox Name="IconComboBox"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

我想在后面的代码中获取ComboBox实例以对其进行操作 .我找到了一篇博客文章,解释了获取ListBoxItem的过程:

I would like to fetch the ComboBox instance in order to manipulate it in the code behind. I found a blog post that explained the process of fetching the ListBoxItem:

ListBoxItem lbi = (ListBoxItem)listBox.ItemContainerGenerator.ContainerFromIndex(IndexInListBox);

但是我找不到在该项目中访问Grid然后访问ComboBox实例的好方法.理想情况下,基于上面的代码,我想做这样的事情:

But I cant find a good way to access the Grid and then ComboBox instances in that item. Ideally, building upon the code above, I would like to do something like this:

ComboBox cb = (ComboBox)lbi.GetChildByName("IconComboBox");

推荐答案

您可以通过模板的FindName方法访问它:

You can access it though the FindName method of the template :

ComboBox cb = (ComboBox)listBox.ItemTemplate.FindName("IconComboBox", lbi);

请注意,只有在ListBoxItem完全加载后才能执行此操作,否则模板不会被实例化

Note that you can only do that after the ListBoxItem is fully loaded, otherwise the template won't be instantiated yet

这篇关于访问ListBoxItem的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆