我正在尝试实现一个IValueConverter,它采用可空类型,例如int?埃纳姆?等等,然后返回bool (如果它有值,则为true,否则为false )。我不知道什么类型的可空的事先。
盒式value (类型为object)没有.HasValue,我也不确定简单的(value == null)是否会反映传递对象的空值,或者是否将任何东西传递给该方法。此外,不可能将value转换为Nullable,而且tehre似乎不是我可以使用的INullable接口。
基本上,我是否需要进行强制转换以确定装箱对象的空值?
这是我拥有的..。
public class NullableHasValueToBool : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
{
// Unsure if this is really the nullness of the passed object
return (value != null);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
{
throw new NotImplementedException();
}
}发布于 2013-08-13 16:35:11
我不确定一个简单的(值为== null)是否会反映传递对象的空性
它会的。
或者如果有什么东西被传递给这个方法,或者没有。
使用HasValue将可空的值传递给False或不向方法传递值基本上是一回事。
private static void Test()
{
System.Diagnostics.Debug.WriteLine(IsNull(new int?())); // Displays True
}
private static bool IsNull(object obj)
{
return obj == null;
}发布于 2013-08-13 16:33:01
这就是我所用的。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
if (value == null)
{
return false;
}
else
{
return !((bool)value ^ param);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool param = bool.Parse(parameter.ToString());
return !((bool)value ^ param);
}https://stackoverflow.com/questions/18214251
复制相似问题