简体   繁体   中英

Converting an integer to a string, through an object

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

    }

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM