Updating the listbox after adding a new item

前端 未结 2 657
走了就别回头了
走了就别回头了 2021-01-24 10:29

I am using WPF and C# I have a button that opens a window, which also includes a button that adds an User object item to a listbox and I want the listbox index to be updated aft

2条回答
  •  灰色年华
    2021-01-24 10:45

    Implementing an observable dictionary is hard. It's much simpler to maintain an parallel observable collection, one that contains the dictionary's values. Bind the view to that collection, and make sure that any code which adds or removes values to/from the dictionary updates the both the dictionary and the parallel collection.

    If you really wanted to go crazy, you could implement a subclass of ObservableCollection to hold your objects, and make that class maintain the dictionary, e.g.:

    public class KeyedObject
    {
        public string Key { get; set; }
        public object Value { get; set; }
    }
    
    public class ObservableMappedCollection : ObservableCollection
    {
        private Dictionary _Map;
    
        public ObservableMappedCollection(Dictionary map)
        {
            _Map = map;    
        }
    
        protected override void InsertItem(int index, KeyedObject item)
        {
            base.InsertItem(index, item);
            _Map[item.Key] = item;
        }
    
        protected override void RemoveItem(int index)
        {
            KeyedObject item = base[index];
            base.RemoveItem(index);
            _Map.Remove(item.Key);
        }
    
        protected override void ClearItems()
        {
            base.ClearItems();
            _Map.Clear();
        }
    
        protected override void SetItem(int index, KeyedObject item)
        {
            KeyedObject oldItem = base[index];
            _Map.Remove(oldItem.Key);
            base.SetItem(index, item);
            _Map[item.Key] = item;
        }
    }
    

    There are a bunch of potential problems in the above, mostly having to do with duplicate key values. For instance, what should SetItem do if you're adding an object whose key is already in the map? The answer really depends on your application. Issues like that also hint at why there isn't an observable dictionary class in the framework.

提交回复
热议问题