views:

55

answers:

2

I have a static ObservableCollection in a Data Repository class. I use it to populate a combobox on one of my forms (which needs to be able to include a blank line which represents NULL).

I use the same ObservableCollection to populate a DataGrid, so I don't want the blank item in the actual ObservableCollection. How do I actually do this?

Oh, and the reason I want to do this is so that if I have both forms open and I delete an item from the ObservableCollection it should reflect that in both of the lists.

+1  A: 

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

<ComboBox ItemsSource={Binding Path=Collection, TargetNullValue="-------"}/>
Val
This doesn't work, perhaps it would work in a different situation and since I didn't post my code, it would be hard to know if I fell under that situation. So no fret, it just doesn't work in my situation.
myermian
+2  A: 
  1. You can't select null value in combobox.
  2. You have to use blank item to display it in the control.
  3. I have the same problem and i'm 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);
    }
    }
    

New collection has one-way binding to base collection:

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

Filtering:

if (this.selectedGroup != null && this.selectedGroup.Id != -1)
    this.MyCollectionView.Filter = v => v.SomeItem.GroupId == this.selectedGroup.Id;
else this.MyCollectionView.Filter = null;
vorrtex
This worked great... Though, I haven't tried the filtering thing yet... I guess I haven't had a need for it. But, changes to the collection with a blank item are updated if the original is altered, which is EXACTLY what I needed.
myermian