Click here to Skip to main content
14,695,505 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
I want to change the enum string value before I display it in a combo box. In this case I want "oranges to display as "Juicy oranges" etc.

<Window x:Class="Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:System="clr-namespace:System;assembly=mscorlib"

        xmlns:local="clr-namespace:FruitProject"

    

    Title="Window1" Height="300" Width="300">
    <Window.Resources>

        
        <local:EnumConverter x:Key="fruitImprover"></local:EnumConverter>
            <ObjectDataProvider MethodName="GetValues"

                        ObjectType="{x:Type System:Enum}"

                        x:Key="deliciousFruits">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:Window1+Fruit" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
        
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height=".25*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        
        <ComboBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Source={StaticResource deliciousFruits}, Converter={StaticResource fruitImprover}}"></ComboBox>
        
    </Grid>
</Window>


The VB code behind window1 is
Public Class Window1
    Public Enum Fruit
        Oranges
        Apples
        Plums
    End Enum
  
End Class


My converter class is:
Public Class EnumConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert

        Dim f As Window1.Fruit = CType(value, Window1.Fruit)
        Select Case f
            Case Window1.Fruit.Apples
                Return "Juicy apples"
            Case Window1.Fruit.Oranges
                Return "Sweet Oranges"
            Case Window1.Fruit.Plums
                Return "Purple Plums"
        End Select

    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return 4
    End Function
End Class


I get the following error message when I try and convert value to a fruit enumeration.

Conversion from type 'Fruit()' to type 'Integer' is not valid.

Any ideas ?
Posted

I would look at the following article: Using DescriptionAttribute for enumerations bound to a ComboBox[^]
   
Yes, don't do it like that (I never managed to get that approach to work0. There is a much better approach you can use which I think is more re-usable. Use the [Description()] Attribute on your enum like this:


Public Enum Fruit
        <Description("Juicy Oranges")>
        Oranges
        <Description("Crunchy Apples")>
        Apples
        Plums
    End Enum


Then use a converter that retrieves description attributes from the bound object.
Public Class EnumDescriptionConverter
	Implements IValueConverter
	Private Function GetEnumDescription(enumObj As [Enum]) As String
		Dim fieldInfo As FieldInfo = enumObj.[GetType]().GetField(enumObj.ToString())

		Dim attribArray As Object() = fieldInfo.GetCustomAttributes(False)

		If attribArray.Length = 0 Then
			Return enumObj.ToString()
		Else
			Dim attrib As DescriptionAttribute = TryCast(attribArray(0), DescriptionAttribute)
			Return attrib.Description
		End If
	End Function

	Private Function IValueConverter_Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
		Dim myEnum As [Enum] = DirectCast(value, [Enum])
		Dim description As String = GetEnumDescription(myEnum)
		Return description
	End Function

	Private Function IValueConverter_ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
		Return String.Empty
	End Function
End Class


Then in your combo box set the datasource to your dataprovider and set the DisplayMemberPath to the converter.

Combobox XAML:

<combobox itemssource="{Binding Source={StaticResource deliciousFruits}}">
            <combobox.itemtemplate>
                <datatemplate>
                    <textblock text="{Binding Converter={StaticResource fruitImprover}}"></textblock>
                </datatemplate>
            </combobox.itemtemplate>
        </combobox>
   
v3
Comments
Hummer463 13-Aug-13 13:34pm
   
I am new to WPF so please bear with me.

If I set DisplayMemberPath="{StaticResource fruitImprover}" I get the following error: An object of the type "FruitImprover.EnumDescriptionConverter" cannot be applied to a property that expects the type "System.String".

If I add a converter ..

ItemsSource="{Binding Source={StaticResource Fruit },Converter={StaticResource fruitImprover}}"

then I get the following error: Unable to cast object of type 'FruitImprover.Fruit[]' to type 'System.Enum'

What am I doing wrong ?

Thanks for the help so far ..
Pheonyx 13-Aug-13 17:17pm
   
Hi, you are almost there, your Combo Box XAML should look something like this:

(see added code to solution)
Hummer463 14-Aug-13 2:02am
   
Yes ! It works !

Thank you.
Pheonyx 14-Aug-13 2:58am
   
No problem, pleased to be able to help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900