Accessing child of ListBoxItem

2019-09-09 08:40发布

问题:

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