views:

258

answers:

1

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  A: 

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

Thomas Levesque
I get the error "This operation is valid only on elements that have this template applied.", both lbi.IsInitialized and lbi.isLoaded reports true. Is the error message caused by the template instantiation problem you warned me about? How can I make sure its loaded?
mizipzor
OK, actually it's not the ListBoxItem you have to pass to the FindName method, but the ContentPresenter which presents the data. You can find an example on the MSDN page of the FindName method: http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx
Thomas Levesque
Yea, I found that out when googling for some more info during the afternoon. I have a short code snippet at work that I plan to post here tomorrow. At the very least to keep the question as a personal reference.
mizipzor