Reputation: 427
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;
}
}
}
Upvotes: 0
Views: 106
Reputation: 612
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
}
Upvotes: 0
Reputation: 157048
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");
}
Upvotes: 1