WPF ObservableCollection: how to add an empty line to a single combobox form but doesnโ€™t really affect the ObservableCollection?

I have a static ObservableCollection in a data repository class. I use it to populate combobox on one of my forms (which should have an empty string that represents NULL).

I use the same ObservableCollection to populate the DataGrid, so I don't need an empty element in the actual ObservableCollection. How am I actually doing this?

Oh, and the reason I want to do this is because if I open both forms and I remove the item from the ObservableCollection, it should reflect this in both lists.

+4
source share
2 answers
  • You cannot select a null value in combobox.
  • You need to use an empty element to display it in the control.
  • I have the same problem and am using this solution in my current project:

    public class ObservableCollectionCopy<T> : ObservableCollection<T> { public ObservableCollectionCopy(T firstItem, ObservableCollection<T> baseItems) { this.FirstItem = firstItem; this.Add(firstItem); foreach (var item in baseItems) this.Add(item); baseItems.CollectionChanged += BaseCollectionChanged; } public T FirstItem { get; set; } private void BaseCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) foreach (var newItem in e.NewItems.Cast<T>().Reverse()) this.Insert(e.NewStartingIndex + 1, newItem); if (e.OldItems != null) foreach (var oldItem in e.OldItems.Cast<T>()) this.Remove(oldItem); } } 

The new collection has one-way binding to the base collection:

 this.SelectableGroups = new ObservableCollectionCopy<GroupModel>( new GroupModel{Id = -1, Title = "Any group"}, this.GroupsCollection); 

Filtration:

 if (this.selectedGroup != null && this.selectedGroup.Id != -1) this.MyCollectionView.Filter = v => v.SomeItem.GroupId == this.selectedGroup.Id; else this.MyCollectionView.Filter = null; 
+5
source

You might be able to use the TargetNullValue property of the TargetNullValue declaration to declare output for a null value.

 <ComboBox ItemsSource={Binding Path=Collection, TargetNullValue="-------"}/> 
+1
source

All Articles