Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update content binding when subproperty changes

Tags:

c#

binding

wpf

I have a label like this:

<Label Name="LblUsersWithHair">
    <Binding Path="Users" 
             ElementName="ElementSelf" 
             Converter="{StaticResource Converter_UsersWithHairPresenter}" />
</Label>

And the converter:

...

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var users = value as ObservableCollection<Users>;
    if (users == null) return null;

    var usersWithHair = users.Count(user => user.HasHair == true);
    return "There are " + usersWithHair + " there has hair.";
}

...

The problem is now that the label of course isn't updated when the 'HasHair' property is changed, since the collection isn't changed. But how do I force the label to rebind, when this property is set?

The example above is very simplified, but hope that you can help me... :o)

like image 543
kahr Avatar asked Sep 18 '26 16:09

kahr


1 Answers

Your Binding will only update, if the list fires a ListChanged-event. This does usually only occur on structural changes (add/remove/replace) in the list, not if a single list item changes - even if it does implement INotifyPropertyChanged. After you have implemented INotifyPropertyChanged for your item, you will still need to do one of the following two options:

  • Use a modified ObservableCollection, that listens to the PropertyChanged-Event of any item within (register on add/remove) and fires ListChanged on any Change.
  • Create a CollectionViewSource with a filter-predicate that evaluates HasHair, then bind your label to the item-count of this CollectionViewSource instead of the original list.
like image 141
Simon D. Avatar answered Sep 21 '26 07:09

Simon D.