Search code examples
wpfxamldata-bindingdictionarydatatemplate

How Do You Bind To An Item In A Dictionary?


I'm using the RadCarousel control from Telerik in a WPF application with C#. RadCarousel is similar to a GridView in that it binds to a collection and show's each item in the collection (so my question isn't specific to Telerik or RadCarousel).

I'm using a DataTemplate to specify how each record should get displayed.

If I do this it work's fine:

<DataTemplate>
    <TextBlock Text="{Binding Path=oMySubObject.TheAmount}" />
</DataTemplate>

But what if I need to point to an item in a dictionary?

<DataTemplate>
    <TextBlock Text="{Binding Path=myDictionaryOfSubObjects[TheCurrentIndex].TheAmount}" />
</DataTemplate>

This I can't get working and don't know how. Basically...I need the index to be specified at runtime and when it gets updated, the binding updates.

Any advice?


Solution

  • <Window.Resources>
      <NAMESPACEWHERECONVERTERRESIDES:DictionaryConverter x:Key="cDictionaryConverter"/>
    </WindowResources>
    
    
        <TextBlock Text="{Binding Path=myDictionaryOfSubObjects, Converter={StaticResource cDictionaryConverter}}"/>
    

    // Something like this:

    [ValueConversion(typeof(Dictionary), typeof(string))]
    public class DictionaryConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
             Dictionary<type, type> dict = value as Dictionary<type, type>; 
             return dict[CurrentIndex].TheAmount; 
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return 0;
        }
    }