Is there a way to add a SortedList or a Dictionary to a ResourceDictionary and use (and bind!) it to a control via XAML?
I’ve tried this, but I couldn’t figure out how to do it:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:coll="clr-namespace:System.Collections.Generic;assembly=mscorlib">
<x:Array x:Key="test"
Type="sys:Object">
<coll:KeyValuePair>***</coll:KeyValuePair>
</x:Array>
SortedListis easy as it is not generic.If a class implements
IDictionaryyou can add values by defining them as the child nodes usingx:Keyto set the key by which they should be added to the dictionary.The item keys are strings here, to get actual ints you could use a custom markup extension which parses the string to int, or by defining the keys as resource first:
The binding then becomes more complex as the indexer value needs to be cast to int explicitly as it otherwise would be interpreted as string.
You cannot omit the
Path=because of an implementation detail.Dictionaries are not so easy because they are generic and there (currently) is no simple built-in way to create generic objects in XAML. Using markup extensions however you can create generic objects via reflection.
Implementing
IDictionaryon such an extension also allows you to fill that newly created instance. Here is a very sketchy example:As passing in a typed instance as key is a bit of a pain i chose to do the conversion in
IDictionary.Addbefore the value is added to the internal dictionary instead (this may cause problems with certain types).Since the dictionary itself is typed the binding should not require a cast.