Accessing child of ListBoxItem

我们两清 提交于 2020-01-16 17:59:45

问题


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>

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);

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");

回答1:


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

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

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



来源:https://stackoverflow.com/questions/1554078/accessing-child-of-listboxitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!