Search code examples
wpfxamlcomboboxrefreshcollectionviewsource

Combobox not updating when bound to CollectionViewSource which is then updated


I have the following:

    <Window.Resources>
        <CollectionViewSource Source="{Binding Categories}" x:Key="Categories"/>
    </Window.Resources>
    ....    
    <ComboBox x:Name="cboCategory" Margin="170,125,0,0" ItemsSource="{Binding Source={StaticResource Categories}}" ItemTemplate="{StaticResource CategoryTemplate}" SelectedValue="{Binding Source={StaticResource Item}, Path=category}" SelectedValuePath="ID" Width="200" Style="{StaticResource RoundedComboBox}" HorizontalAlignment="Left" VerticalAlignment="Top"/>        

Then in code

    Private _Categories As ObservableCollection(Of CategoryEntry)
    Public Property Categories As ObservableCollection(Of CategoryEntry)
        Get
            Return _Categories
        End Get
        Set(value As ObservableCollection(Of CategoryEntry))
            _Categories = value
        End Set
    End Property

    .....

    strSelect = "SELECT * FROM Categories WHERE Categories.comment<>'Reserved' ORDER BY Categories.comment"
    dsccmd = New OleDbDataAdapter(strSelect, cn)
    dsccmd.Fill(dsc, "Categories")
    dvc = New DataView(dsc.Tables("Categories"))
    _Categories = New ObservableCollection(Of CategoryEntry)(dvc.ToTable.AsEnumerable().[Select](Function(i) New [CategoryEntry](i("ID"), i("comment").TrimEnd(" "), i("work"), If(i("work"), New SolidColorBrush(Colors.CornflowerBlue), New SolidColorBrush(Colors.White)))))
    Me.DataContext = Me

This works fine. However if I change the contents of _Categories eg. using code as above setting _Categories = New ObservableCollection...... the combobox is not updated.

I have tried using CollectionViewSource.GetDefaultView.Refresh and ComboBox.UpdateLayout with no success

Help!

Thanks Andy


Solution

  • Your not actually updating your ObservableCollection, your just replacing it.

    If you replace the reference you need to raise the propertychanged-event:

    Private _Categories As ObservableCollection(Of CategoryEntry)
    Public Property Categories As ObservableCollection(Of CategoryEntry)
        Get
            Return _Categories
        End Get
        Set(value As ObservableCollection(Of CategoryEntry))
            _Categories = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArg("Categories"))
        End Set
    End Property
    

    This is of course supposing that the class implements INotifyPropertyChanged