Search code examples
c#silverlightdata-bindingcomboboxivalueconverter

IValueConverter for collection


I have ComboBoxes than bind to collections of type int or double in my Silverlight application. These collections hold the possible valid values that can be selected by the user. I need to also have an "Auto" option in the ComboBox. In my code, I am representing "Auto" as -1. So, I am trying to find a way that I can take a collection of ints (with the possibility of the collection containing -1) and bind a ComboBox to it, with an IValueConverter making the -1 show up as "Auto". I have tried setting the Converter in the Binding on ItemsSource, but am having trouble creating a new collection with the formatted options.


Solution

  • I decided to try one more search before posting this question and finally came across my answer. The key in this situation is to not use the IValueConverter as the Converter for the ItemsSource binding, but rather to set up an ItemTemplate (I use it in a style):

    <Style TargetType="ComboBox" x:Key="AutoComboBox">
        <Setter Property="ItemTemplate">
            <DataTemplate>
                <TextBlock Text="{Binding Converter={StaticResource autoConverter}}" />
            </DataTemplate>
        </Setter>
    </Style>
    

    The autoConverter is just a simple implementation of IValueConverter that checks if the value is -1, and if so it returns "Auto". ConvertBack does vice-versa.