A strange question related to the disappearance of objects

I have a ComboBox, which as an ObservableCollection is its source. Thus, the ComboBox consists of shortcuts.

I have several UserControls that can be created by the user, and each of these UserControls can have multiple ComboBoxes. When a UserControl is created, a label named UserControl is added to the ObservableCollection, so every ComboBox whose source object is an ObservableCollection will now add the last label to it.

Everything works fine, and ComboBoxes populate as new UserControls arrive, as expected. However, a very strange problem arises.

When a user opens the combo box of a single UserControl, he can correctly see all the shortcuts.

Then, when the user opens the ComboBox drop-down menu of another UserControl, all items are displayed the same way. Now the weird problem is that when the user returns to the ComboBox of the previous UserControl, the elements disappear. Shortcuts still exist, since I debugged them and found that the labels are still contained as elements, however it is as if their height was set to 0 (during debugging it was found that their height is not 0, but 26 in fact).

The same number of shortcuts is contained, and, as seen in the screenshot above, they can be selected, but not visible (only this small blue bar can be shown to show that it selects something). I’m not changing the height of the label anywhere.

The user commented that WPF caches CollectionView with the collection that it represents, so all ComboBoxes use the same CollectionView instance. Therefore, a label can have only one visual parent, so when the user expands the second ComboBox, it separates the labels from the first.

+4
source share
1 answer

Here is the solution. Modify the ComboBox as follows and bind the ObservableCollection<T> to the ComboBox . Note that you must 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> 

Hope this helps.

+1
source

All Articles