WPF - bind a listbox to a list<string> - what am I doing wrong?

大憨熊 提交于 2019-12-06 14:19:15

You should use BindingList<T> or ObservableCollection<T> instead of List<T>.

The problem is that, for binding to work the way you want, it needs to implement INotifyCollectionChanged or IBindingList. List<T> does not support this.


Edit:

After reviewing your changes, there is still one problem.

In the AddFileButton_Click event handler, remove the following line:

SelectedItems.ItemsSource = null;

It is explicitly removing your binding, and causing the list box to clear. If you remove that, your code should work as-is.

However, I do recommend changing your collection definition and constructor to something more like:

    // No need for the null checking every time, or public setter.  They just cause issues
    public ObservableCollection<string> ItemList
    {
        get;
        private set;
    }

    // Add construction here, now that we're using an auto-prop
    public Main()
    {
        this.ItemList = new ObservableCollection<string>();
        InitializeComponent();
        ItemList.Add("test item");
        DataContext = this;
    }

I don't like this getter... personally. Looks conspicuous.

get { return _itemList ?? (_itemList = new ObservableCollection<string>()); }

You're already initializing the _itemList in the declaration. If you need to do it double time to feel safe, do it in the constructor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!