0

I want to force the binding of my Listbox to refresh its content. My listbox is bounded to a dependency property:

<ListBox ... DataContext="{Binding ElementName=_this}" ItemsSource="{Binding Path=MyList}"/>

I want to refresh the listbox content when, for example, I press a button in such a way that the DependencyProperty MyList get is called.

Sean
  • 15
  • 2

2 Answers2

2

You could make MyList an ObservableCollection, or something else which implements INotifyCollectionChanged

Then if you changed the contents of MyList the ListBox would be updated automatically

In this case you wouldn't even need to declare MyList as dependency property. A simple readonly property would be sufficient:

public ObservableCollection<MyItem> MyList { get; }
    = new ObservableCollection<MyItem>();
Clemens
  • 123,504
  • 12
  • 155
  • 268
Chris Barber
  • 513
  • 4
  • 10
-1

Use an ObservableCollection as the container for the items you want to display in the ListBox. This will automatically trigger a refresh of the control when items are added or removed.

Since you now never need create a new collection (only refresh its contents), you can use a regular C# property for this.

Personally, I would abstract this out

private ObservableCollection<MyItem> _mylist = new  ObservableCollection<MyItem>();
public IEnumerable<MyItem> MyList => _mylist;

To refresh the list ...

_myList.Clear();
_mylist.Add( ... );

The control will still update, as it detects that MyList implements INotifyCollectionChanged, even though it is just declared as IEnumerable.

You should never use a DependencyProperty for the source of data binding - a regular property, combined with INotifyPropertyChanged is the preferred way for any properties that update their value. Take a look at the MVVM pattern as a way of separating the user interface from the remainder of the code.

Peregrine
  • 4,287
  • 3
  • 17
  • 34