【问题标题】:How to implement a NullableHasValueToBool IValueConverter如何实现 NullableHasValueToBool IValueConverter
【发布时间】:2013-08-13 16:21:17
【问题描述】:

我正在尝试实现一个IValueConverter,它采用可空类型,例如诠释?枚举?等等,并返回一个布尔值(如果它有一个值,则为 true,否则为 false)。我事先不知道可为空的类型。

装箱的valueobject 类型)没有.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();
    }
}

【问题讨论】:

    标签: c# silverlight windows-phone-7 ivalueconverter


    【解决方案1】:

    我不确定一个简单的 (value == 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;
    }
    

    【讨论】:

      【解决方案2】:

      这是我用的。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多