IValueConverter from string

Posted by Aleksandar Toplek on Stack Overflow See other posts from Stack Overflow or by Aleksandar Toplek
Published on 2012-09-18T14:46:02Z Indexed on 2012/09/18 15:38 UTC
Read the original article Hit count: 376

Filed under:
|
|
|
|

I have an Enum that needs to be shown in ComboBox. I have managed to get enum values to combobox using ItemsSource and I'm trying to localize them. I thought that that could be done using value converter but as my enum values are already strings compiler throws error that IValueConverter can't take string as input. I'm not aware of any other way to convert them to other string value. Is there some other way to do that (not the localization but conversion)?

I'm using this marku extension to get enum values

[MarkupExtensionReturnType(typeof (IEnumerable))]
public class EnumValuesExtension : MarkupExtension {
    public EnumValuesExtension() {}

    public EnumValuesExtension(Type enumType) {
        this.EnumType = enumType;
    }

    [ConstructorArgument("enumType")]
    public Type EnumType { get; set; }
    public override object ProvideValue(IServiceProvider serviceProvider) {
        if (this.EnumType == null)
            throw new ArgumentException("The enum type is not set");
        return Enum.GetValues(this.EnumType);
    }
}

and in Window.xaml

<Converters:UserTypesToStringConverter x:Key="userTypeToStringConverter" />
....
<ComboBox ItemsSource="{Helpers:EnumValuesExtension Data:UserTypes}" 
            Margin="2" Grid.Row="0" Grid.Column="1" SelectedIndex="0" TabIndex="1" IsTabStop="False">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type Data:UserTypes}">
            <Label Content="{Binding Converter=userTypeToStringConverter}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And here is converter class, it's just a test class, no localization yet.

public class UserTypesToStringConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        return (int) ((Data.UserTypes) value) == 0 ? "Fizicka osoba" : "Pravna osoba";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
         return default(Data.UserTypes);
     }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf