我是XAML和WPF的新手,我正在尝试构建一个转换器,它将一个整数转换为一个月(字符串) 我知道下面的代码不起作用,因为它得到一个对象而不是一个字符串来处理,但我不知道如何处理这个对象?
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 :(得分:1)
您非常接近,只需在value
检查int
之后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");
}
:
{{1}}
答案 1 :(得分:0)
为什么不使用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
}