Search code examples
mvvmcross

Is there a way to bind a Dictionary in mvvmcross


I started using observable ConcurrentDictionary because it's threadsafe. But now I face a problem how to bind it to the list.

local:MvxBind="ItemsSource SourceDictionary" 

obviously cannot work because item consists of the KeyValuePair and not the object itself.

local:MvxBind="ItemsSource SourceDictionary.Values"

does not work. Which, I must admit, puzzles me. I even tried a long shot and did some converter :

public class SourceDictionaryValueConverter : MvxValueConverter<KeyValuePair<string, SourceClass >, SourceClass >
{
    protected override SourceClass Convert(KeyValuePair<string, SourceClass> value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.Value;
    }
}

and bind it like this

local:MvxBind="ItemsSource SourceDictionary, Converter=SourceDictionary"

but it didn't work. I suppose it asks for IList. Is there any way to bind ListView to the Dictionary?


Solution

  • You should be able to bind to a Dictionary - or indeed to any IEnumerable.

    If you are binding to the Dictionary itself (rather than to Values) then you will need to write your item bindings so that they know about KeyValuePair - e.g. so you might need to bind to Key.Name rather than to just Name.

    However, Dictionary's themselves do not notify listeners of changes - so using a Dictionary is like using a List - not like using an ObservableCollection. If you want this type of behaviour then you will need to write or find a Dictionary class which implements INotifyCollectionChanged.