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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With