Bind to Count of items in the DataContext

后端 未结 5 1241
别跟我提以往
别跟我提以往 2021-02-12 03:45

I want to bind to the Count/amount of items within my DataContext.

I have an object, lets say person which has a List

as a property. I would
5条回答
  •  死守一世寂寞
    2021-02-12 03:57

    As tehMick says, you can bind using the path Addresses.Count.

    Note, however, that unless Addresses is an ObservableCollection

    , or some other type that implements INotifyCollectionChanged, adding and removing addresses won't affect the number that appears in the UI after its initial display. If you need that, you will either need to change the type of the collection in your view model (that's easiest), or implement a property in your view model that exposes the count, and raise the PropertyChanged event every time you add or remove an address.

    Edit

    I love reading an answer, thinking, "hey, that's not right," and then realizing I wrote it.

    If you bind to an object that just implements INotifyCollectionChanged, the count in the UI won't change if items are added or removed ot the collection. The object also has to implement INotifyPropertyChanged and raise PropertyChanged when the Count property changes.

    Which, fortunately, ObservableCollection does. So my answer's not that wrong.

提交回复
热议问题