开发者

Binding to an ObservableCollection<T> and using a ValueConverter

I'm trying to bind an ObservableCollection<T> to a TreeView (or any other control for that matter) via a ValueConverter. In the ValueConverter, I use the AsHierarchy extension (scip.be) to transform a Self-Referencing (each entity has a ParentId field) into a hierarchy.

As mentioned, I store my (flat list of) entities in inside an ObservableCollection<T> where the updates to the list are reflected on the view (GUI) when I don't use the ValueConverter.

If I add the ValueConverter, the updates aren't reflected on my view any more and if I set a break point inside the value converter, I notice that it is only called once on load, ignoring all further CollectionChanged events.

Source code of the ValueConverter:

publi开发者_运维问答c class HierarchyValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;
        ObservableCollection<Entity> data = (ObservableCollection<Entity>)value;
        return data.AsHierarchy(p => p.Id, p => p.ParentId);
    }

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

The ItemsSource where I bind the converter:

ItemsSource="{Binding Data,
                      Source={StaticResource MyDataSource},
                      Converter={StaticResource HierarchyValueConverter}}"

I hope someone can provide an answer, since this one's bugging me for quite some time now.

Thank you in advance!


Binding a hierarchy in an observable way will almost certainly not be solved by one extension method.

I would suggest you implement your own utility class, something like the CompositeCollection but of course aimed at an hierarchical setup, rebuilding the whole tree if one item is added will quickly become unviable otherwise. This possibly is not a trivial task but that is the general direction i would recommend.


ObservableCollection implements interface INotifyCollectionChanged which notifies your itemscontrol that something has changed. AsHierarchy just returns an IEnumerable which do not provide change notification and therefor you will no longer see updates.

Quick and dirty fix is to subscribe to the ObservableCollection's CollectionChanged event. In the event handler, force a rebind so the value converter's Convert method runs again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜