Where did my ComboBox selected item go?

You might have noticed that sometimes the item in the selection box of a combo box disappears when you reopen the drop-down of the combo.

For example, in the following image, "Arial" is selected,


but doesn't show up in the selection box when the drop-down is reopened.


In contrast, in the following ComboBox, the selected item, "Courier New", is visible in the selection box when the drop-down is reopened.


Here's the code for the first combo box:

<ComboBox x:Name="myCombo" Width="150" Margin="10">
    <ComboBoxItem Content="Arial" />
    <ComboBoxItem Content="Courier New" />
    <ComboBoxItem Content ="Times New Roman" />

The reason the selected item disappears is because a UIElement cannot be in the visual tree more than once. In the first case, I've explicitly created ComboBoxItems and set their content to font names. ComboBoxItem is a UIElement and when it is in the drop-down, it can't be shown in the selection box. When the drop down is closed the UIElement is temporarily moved in the visual tree to be shown as the selected item. This occurs for all UIElements in a Silverlight combo box.

CLR objects that are not derived from UIElement do not have this limitation. In the second case the items are added to the combo box through a binding. The combo box is bound to a collection of strings:

<ComboBox x:Name="FontsCombo" Height="20" Width="150"
    ItemsSource="{Binding}" />

ObservableCollection<string> fonts =
    new ObservableCollection<string>();
fonts.Add("Courier New");
fonts.Add("Times New Roman");
FontsCombo.DataContext = fonts;

When CLR objects are used to populate a combo box, UIElements are automatically generated for them using the data template (in this case the default data template is a TextBlock). Two different UIElements are created so CLR objects can be shown in both the selection box and drop-down at the same time.

Hopefully this clears up any confusion. Also this info is now in the online docs.


Comments (6)

  1. Beatle.still says:

    http://still.pe.kr/tc/396 – where-did-my-combobox-selected-item-go

    thanks 🙂

  2. spam-dev says:

    How do you set selectItem or SelectIndex from binding data?

    thank you.

  3. jonaskello says:

    Thanks for the explaination, this was driving me crazy 🙂

  4. Sachin P says:

    Thanks Cheryl.. this Approach still works in 2012… Is this a issue in Silverlight?

  5. AshokRaj says:

    Can you please Upadte Is this problem solved or not

Skip to main content