Arihant
Arihant

Reputation: 367

wpf IValueConverter not updating the view

I am trying to use IValueConverter to convert the collection into proxy object for data binding.

The converter seems to work fine, but the problem is when a new object is added or removed from the collection. The same is not refreshed in the view..

Model Object:

public class A {
   public ObservableCollection<string> Members { get; }
}

Converter

public class MemberConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        var collection = new CompositeCollection();
        var a = value as A;

        a.Members.ToList().ForEach(member => {
            collection.Add(new ProxyClass{ A= a, Member= member });
        });

        return collection; 
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new System.NotImplementedException();
    }
}

Proxy Class

public class ProxyClass {
    public A A { get; set; }

    public string Member{ get; set; }
 }

XAML:

<DataTemplate DataType="{x:Type my:ProxyClass}">
            <TextBlock Text="{Binding Path=Member}"/>
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type A}" ItemsSource="{Binding Converter={StaticResource MemberConverter}}">
            <TextBlock Text ="{Binding}"/>
</HierarchicalDataTemplate>

Upvotes: 2

Views: 4126

Answers (2)

AndrewS
AndrewS

Reputation: 6094

A Binding will only be re-evaluated if a property change notification for the property to which it is bound has been changed. In this case the ItemsSource is bound to the DataContext - the A instance itself - so unless it is given a new A instance it will not be re-evaluated. There is nothing listening to the change notifications that the collection raises since the value given to the ItemsSource is actually a different collection instance that you are creating within your converter.

One option would be to have the converter create a helper class that hooks the CollectionChanged event of the source collection (i.e. the value passed into the converter) and that object would be responsible for keeping the source collection and the one it creates in sync. Another option is to try to force the binding to get re-evaluated - e.g. use a Path of "Members" for the ItemsSource binding and when you change the contents of the collection raise a property change notification for "Members" on A.

Upvotes: 2

MyKuLLSKI
MyKuLLSKI

Reputation: 5325

Its not updating because your A Property doesn't implement INotifyPropertyChanged or is a DependencyProperty

If need be you can add the following after making it implement one of the previous.

ItemsSource="{Binding Converter={StaticResource MemberConverter}, UpdateSourceTrigger=PropertyChanged}">

Upvotes: 1

Related Questions