gpt4 book ai didi

c# - WPF ObservableCollection : How to add a blank line in one form's combobox, 但实际上不影响ObservableCollection?

转载 作者:太空狗 更新时间:2023-10-30 00:58:00 24 4
gpt4 key购买 nike

我在数据存储库类中有一个静态 ObservableCollection。我用它来填充我的一个表单上的组合框(需要能够包含一个代表 NULL 的空行)。

我使用相同的 ObservableCollection 来填充 DataGrid,因此我不希望实际 ObservableCollection 中的空白项。我该怎么做?

哦,我想这样做的原因是,如果我打开两个表单并从 ObservableCollection 中删除一个项目,它应该在两个列表中反射(reflect)出来。

最佳答案

  1. 不能在组合框中选择空值。
  2. 您必须使用空白项才能在控件中显示它。
  3. 我有同样的问题,我正在我当前的项目中使用这个解决方案:

    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);
    }
    }

新集合具有与基础集合的单向绑定(bind):

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

过滤:

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

关于c# - WPF ObservableCollection : How to add a blank line in one form's combobox, 但实际上不影响ObservableCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3876557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com