I'm having an issue with a pair of combo box's in Silverlight 4.0.
The intention is to have two different comboboxes that read from the same list, but if any item selected in one won't show up in the other (as the underlying properties are not allowed to be the same).
E.g. (this is just example code, but identically represents how it works)
<ComboBox ItemsSource="{Binding BackgroundColors}"
SelectedItem="{Binding SelectedBackgroundColor, Mode=TwoWay}" />
<ComboBox ItemsSource="{Binding ForegroundColors}"
SelectedItem="{Binding SelectedForegroundColor, Mode=TwoWay}" />
To allow for this dynamic filtering, I have 2 different ICollectionView
's in my ViewModel that each combo box ItemsSource
is bound to. Each ICollectionView
has a source of the same ObservableCollection<T>
but in the filter is set to filter out the other's selected item.
private ObservableCollection<Color> _masterColorList;
public ICollectionView BackgroundColors { get; }
public ICollectionView ForegroundColors { get; }
When a SelectedItem is changed in the UI, the ViewModel properties are updated, and as part of that, the opposite ICollectionView
is refreshed via .Refresh()
.
Eg.
public Color SelectedForegroundColor
{
get { return _selectedForegroundColor; }
set
{
if (_selectedForegroundColor == value)
return;
_selectedForegroundColor = value;
BackgroundColors.Refresh();
RaisePropertyChanged(() => SelectedForegroundColor);
}
}
This allows the filter to rerun and change what is available to be selected.
This works pretty well, but there is a problem:
Say we have 3 colors in our master list:
- Blue
- Green
- Red
Combo box 1 (CB1) is has selected Blue Combo box 2 (CB2) has selected Green
Thus the combo boxes have these lists (bold is selected)
CB1
- Blue
- Red
CB2
- Green
- Red
If I then select Red in CB1, I would expect that Red would be removed from CB2 and Blue replace it. This happens correctly, BUT the displayed value changes from Green to Blue.
The underlying bound value doesn't get changed and the ICollectionView.CurrentItem is correct, but the display is clearly showing the wrong value.
What I think is happening is that because Green is earlier in the list, that it is getting confused with what is being shown. It also occurs if you are sorting the ICollectionView.
I've tried re-raising the property changed event notification for the changing combobox & selected item but this doesn't seem to work.
Has anyone seen this issue before or any ideas how I could fix it?
There are at least 5 serious issues with binding of comboboxes.
Here I think you ran into
http://connect.microsoft.com/VisualStudio/feedback/details/523394/silverlight-forum-combobox-selecteditem-binding
this one.
Once you update itemssource binding stops working.
I used one of solutions available there, this code solved this issue for me:
Its not mine code, but one from articles related to this bug.