Share via


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,

selectionBox

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

itemdisappeared

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

itemStillThere

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" />
</ComboBox>

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("Arial");
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.

--Cheryl

Comments

  • Anonymous
    December 02, 2008
    PingBack from http://blog.a-foton.ru/index.php/2008/12/03/where-did-my-combobox-selected-item-go/

  • Anonymous
    December 02, 2008
    http://still.pe.kr/tc/396 - where-did-my-combobox-selected-item-go thanks :)

  • Anonymous
    June 14, 2010
    How do you set selectItem or SelectIndex from binding data? thank you.

  • Anonymous
    July 20, 2010
    The comment has been removed

  • Anonymous
    July 26, 2012
    Thanks Cheryl.. this Approach still works in 2012... Is this a issue in Silverlight?

  • Anonymous
    November 30, 2015
    Can you please Upadte Is this problem solved or not