How to: Get a ComboBoxItem

When you bind a ComboBox to a data source, you often need to get to the ComboBoxItem to perform a certain action. You can get the ComboBoxItem by using an ItemContainerGenerator. The following example shows a ComboBox that is bound to a data source called myCities.


<ComboBox Name="cb" Margin="10,10,3,3" Width="200" Height="30" Grid.Column="0" Grid.Row="2"         
          ItemsSource="{StaticResource myCities}" Text="My Cities"
          IsEditable="true"  IsReadOnly="true" 
          IsDropDownOpen="True" StaysOpenOnEdit="True">
</ComboBox>


You can get the ComboBoxItem by using the ItemContainerGenerator.ContainerFromIndex method and specifying the index of the item you want. The following example gets the ComboBoxItem by specifying the index of the item and then selects that item in the ComboBox.


private void GetComboBoxItem(int index)
{
    ComboBoxItem cbi = (ComboBoxItem)
         (cb.ItemContainerGenerator.ContainerFromIndex(index));

    cbi.IsSelected = true;
    Info.Content = "I visited " +
         (cbi.Content.ToString()) + ".";
}


Sometimes you will have the object of the item in the data source but not know its index. In that case, you can use the ItemContainerGenerator.ContainerFromItem method to get the ComboBoxItem. The following example gets the ComboBoxItem by specifying the object in the collection and then selects that item in the ComboBox.


ComboBoxItem cbi = (ComboBoxItem)
    cb.ItemContainerGenerator.ContainerFromItem(objectInCollection);

cbi.IsSelected = true;


Show:
© 2014 Microsoft