Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to Count of items in the DataContext

Tags:

binding

wpf

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

I have an object, let's say person which has a List<address> as a property. I would like to display the amount of addresses for that person, i.e.: 5 or 6 or whatever the case may be.

I've tried {Binding Path=address#.Count} and a few others but that doesn't seem to work.

like image 858
Organ Grinding Monkey Avatar asked May 26 '10 20:05

Organ Grinding Monkey


2 Answers

You need to bind the name of the property, not its type.

C#:

public class Person {     ...     public List<address> Addresses { get; set; }     ... } 

XAML:

{Binding Addresses.Count} 

Assuming your DataContext is an object of type Person.

like image 60
Eric Mickelsen Avatar answered Oct 08 '22 22:10

Eric Mickelsen


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

Note, however, that unless Addresses is an ObservableCollection<address>, 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<T> does. So my answer's not that wrong.

like image 25
Robert Rossney Avatar answered Oct 08 '22 21:10

Robert Rossney