[英]How to implement a NullableHasValueToBool IValueConverter
我正在嘗試實現一個IValueConverter
,它采用可為空的類型,例如int? 枚舉? 等等,並返回布爾值(如果有值,則返回true,否則返回false)。 我不知道可為空的類型。
裝箱的value
(類型為object
)沒有.HasValue
,我不確定一個簡單的(value == null)
不會反映所傳遞對象的空性,或者是否將任何內容傳遞給該方法。 此外,不可能將value
強制轉換為Nullable
並且thre似乎不是我可以使用的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();
}
}
我不確定一個簡單的(value == null)是否會反映所傳遞對象的無效性
它會。
或者是否有任何東西傳遞給該方法
將具有HasValue
的nullable傳遞為False或不將任何值傳遞給方法基本上是同一回事。
private static void Test()
{
System.Diagnostics.Debug.WriteLine(IsNull(new int?())); // Displays True
}
private static bool IsNull(object obj)
{
return obj == null;
}
這就是我用的。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.