开发者

WPF ObservableCollection: How to add a blank line in one form's combobox, but not actually affect the ObservableCollection?

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. 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;


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="-------"}/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜