Updating the listbox after adding a new item

前端 未结 2 629
走了就别回头了
走了就别回头了 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:43

    The easiest way is to use System.Collections.ObjectModel.ObservableCollection as your list. This implements INotifyCollectionChanged and INotifyPropertyChanged for you.

    You would have a property on your DataContext object of this type, and use data binding on ListBox.ItemsSource to bind it to that property. The ListBox will automatically update its list of elements when the collection changes.

    In the class that is your DataContext:

    public class MyClass
    {
        public ObservableCollection Items { get; set; }
    }
    

    In Xaml:

    
    
    

    It sounds like you also want an observable dictionary, but unfortunately there is not one built into the framework. You could try using Dr. Wpf's implementation of ObservableDictionary from his post "Can I bind my ItemsControl to a dictionary?".

提交回复
热议问题