我有以下内容:
<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"/>
然后在代码中
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
这很好用。但是,如果我改变_Categories的内容,例如。使用上面的代码设置_Categories = New ObservableCollection ......组合框不会更新。
我尝试过使用CollectionViewSource.GetDefaultView.Refresh和ComboBox.UpdateLayout但没有成功
帮助!
由于 安迪
答案 0 :(得分:0)
你实际上没有更新你的ObservableCollection,你只需要替换它。
如果替换引用,则需要引发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
这当然是假设该类实现了INotifyPropertyChanged
答案 1 :(得分:0)
那是Bindings的常用行为。如果你“制作”一个新的ObservableCollection,你必须“制作”一个新对象到新对象,因为绑定是一个现在已经不存在的对象,你用之前创建的新对象替换它。最好的办法是你创建一个_Categories.Clear(),然后将内容添加到它(使用.AddRange(new ObservableCollection(...))或其他东西)。