0

I'm pretty new to XAML and WPF, and I'm trying to build a Converter, which converts an integer to a month (string) I know the code below doesn't work because it gets an object rather than a string to process, but I have no idea how to handle this object?

  public class NumberToMonthConverter : IValueConverter
    {   
        public object Convert(object value, Type targetType,
  object parameter, CultureInfo culture)
        {                
            if (value is int)
            {
                string strMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(value);
                return strMonthName;
            }   
        }

    }
0

2 Answers 2

1

You are pretty close, just cast value to int after you checked it is an int:

if (value is int)
{
    return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName((int)value);
}
else // you need this since you need to return a value
{    // throw an exception if the value is unexpected
    throw new ArgumentException("value is not an int", "value");
}
Sign up to request clarification or add additional context in comments.

2 Comments

And there should be an else to the check or it won't compile since not all paths return a value.
I was just quoting (well, misquoting) the c# compiler error message. I'd probably go with an exception too.
0

why dont use TryParse?

int i;
if (int.TryParse(value, out i)) {
            string strMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i);
            return strMonthName;
}
else  {
    throw new Exception("value is not int!");
    --OR--
    return "Jan"; //For example
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.