Lai32290
Lai32290

Reputation: 8578

Update automatic ListBox items when alter List<T>

I have a ListBox, I populate it with ItemsSource with List<Control>.

But when I delete or add new control for this List, I need every time reset my ListBox ItemsSource

Have any method for ListBox sync List content?

Upvotes: 0

Views: 129

Answers (3)

Arushi Agrawal
Arushi Agrawal

Reputation: 629

Implement INotifyPropertyChanged interface in your viewmodel. Post that in the setter of this List, call the NotifyPropertyChanged event. This will result in updating your changes on UI

Upvotes: 0

Gayot Fow
Gayot Fow

Reputation: 8812

In your Xaml, use something like this...

<ListBox ItemsSource="{Binding MyItemsSource}"/>

And wire it up like this...

public class ViewModel:INotifyPropertyChanged
    {
        public ObservableCollection<Control> MyItemsSource { get; set; }
        public ViewModel()
        {
            MyItemsSource = new ObservableCollection<Control> {new ListBox(), new TextBox()};
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }

This will present the items to the ListBox. In the example here, the collection contains a ListBox and a TextBox. You can add/delete from the collection and get the behaviour you are after. Controls themselves are not all that great as ListBox items because they do not have a meaningful way of populating a visual. So you will probably need to run them through an IValueConverter.

Upvotes: 2

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

Instead of using a List<T>, use an ObservableCollection<T>. It is a list that supports change notifications for WPF:

// if this isn't readonly, you need to implement INotifyPropertyChanged, and raise
// PropertyChanged when you set the property to a new instance
private readonly ObservableCollection<Control> items = 
    new ObservableCollection<Control>();

public IList<Control> Items { get { return items; } }

Upvotes: 2

Related Questions