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;
            }   
        }

    }
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
user3208179
  • 367
  • 1
  • 6
  • 12

2 Answers2

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");
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • And there should be an else to the check or it won't compile since not all paths return a value. – Chris Aug 19 '14 at 11:59
  • 1
    I was just quoting (well, misquoting) the c# compiler error message. I'd probably go with an exception too. – Chris Aug 19 '14 at 12:03
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
}
Emran Sadeghi
  • 612
  • 6
  • 20