Dot NET
Dot NET

Reputation: 4907

Strange issue involving disappearing items

I've got a ComboBox which as an ObservableCollection as its item source. Thus, the ComboBox is made up of Labels.

I've got a number of UserControls which can be spawned by the user, and each one of these UserControls can have a number of ComboBoxes. When a UserControl is created, a label with the UserControl's name is added to the ObservableCollection, thus every ComboBox whose item source is the ObservableCollection, would now have the latest label added to it too.

Everything works fine, and the ComboBoxes are populated as new UserControls are spawned, as expected. However, a very strange issue is occuring.

When the user opens the ComboBox drop down menu of one UserControl, he can see all the labels properly.

Then, when the user opens the ComboBox drop down menu of another UserControl, the items are all displayed in the same manner. Now the strange issue is that when the user goes back to the ComboBox of the previous UserControl, the items disappear. The labels are still there, as I have debugged it and found that the labels are still contained as items, however it is as if their height has been set to 0 (on debugging it was found that their height was not 0, but 26 in fact).

The same amount of labels are contained, and as can be seen in the screenshot above, they are selectable, however not visible (just that tiny blue bar can be seen to show that it's selecting something). I am not changing the label's height anywhere.

A user has commented that WPF caches CollectionView by the collection it represents so all the ComboBoxes share the same instance of CollectionView. Hence, a Label could have only one visual parent, so when the user expands the second ComboBox it detaches labels from the first one.

Upvotes: 4

Views: 154

Answers (1)

Dilshod
Dilshod

Reputation: 3331

Here is solution. Change your ComboBox like this and bind your ObservableCollection<T> to ComboBox. Note that you should change the ObservableCollection<Label> to ObservableCollection<string>.

<ComboBox x:Name="cmb1" Height="24" Margin="0,27,0,0" VerticalAlignment="Top" Width="131">
   <ComboBox.ItemTemplate>
       <DataTemplate>
           <Label Content="{Binding}"/>
       </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>

I hope this helps.

Upvotes: 1

Related Questions