Creating a generic value converter

Hi all. I wanted to create a value converter which would take two enum values and return true if they are equal. For some reason though the value converter only works if I specify the enum type in the comparision and won't work if I just compare the value and converter.

i.e.

This would show is State.ChosenAnswer = TypeOfAnswer.A

<ContentView IsVisible="{Binding State.ChosenAnswer, Converter={StaticResource EnumEquals}, ConverterParameter={x:Static enum:TypeOfAnswer.A}}">

Here is my converter;

    public class EnumEqualsBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //return parameter == value;  This doesn't work
            // This does work
            var selectedAnswer = (TypeOfAnswer)value;
            var thisAnswer = (TypeOfAnswer)parameter;
            return selectedAnswer == thisAnswer;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return false;
        }
    }

You can see if I specify the enum type I have no problem but just comparing the two doesn't (even though Visual Studio code eval tells me they are equal / unequal when I debug in)

Answers

  • PaulKiarPaulKiar USMember ✭✭

    I'm going to try something similar, if I figure it out I'll let you know. Have you tried Object.Equals(value,parameter)?

  • PaulKiarPaulKiar USMember ✭✭
    edited March 2017

    Here's how you do it:
    public class EnumEqualsBooleanConverter<T> : IValueConverter where T : struct
    in your convert just do:
    return (T)selectedAnwser == (T)thisAnswer;

    In your xaml:
    <ResourceDictionary> <converters:EnumEqualsBooleanConverter x:TypeArguments="<xmlns>:<enumType>" x:Key="enumEquals"/> </ResourceDictionary>

  • PaulKiarPaulKiar USMember ✭✭
    edited March 2017

    I don't post much and really screwed up my first post

  • 40Alpha40Alpha Member ✭✭

    Thanks Paul.

Sign In or Register to comment.