C#:WPF 多值转换器检查对象 [] 是否为空



现在我正在使用WPF并创建自定义MessageControl。消息控件具有 2 个属性:
1. 字符串详细信息
2. 字符串解决方案
我有实现IMultiValueConverter的可见性转换器,Convert方法中我需要检查详细信息和解决方案。如果"详细信息"或"解决方案"未null,则不string.Empty或不DependencyProperty.UnsetValue我需要返回Visibility.Visible。问题是values转换器参数object[]。如果我这样做values[0].ToString()并且当values[0]为空时,会在此处抛出异常。现在我的代码可以工作了,但它是很多行代码。我的变体在这里:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //if Detail or Solution is not null,not empty and not UnsetValue than show control
            if (values[0] != null && values[0] != DependencyProperty.UnsetValue)
            {
                if (values[0].ToString() != string.Empty)
                {
                    return Visibility.Visible;
                }
            }
            if (values[1] != null && values[1] != DependencyProperty.UnsetValue)
            {
                if (values[1].ToString() != string.Empty)
                {
                    return Visibility.Visible;
                }
            }
            return Visibility.Collapsed;
        }

有没有最好的方法可以用最少的代码行来检查它?
提前感谢!

这样的事情应该有效(试试吧,我没有):

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Any(v => v == null || v == DependencyProperty.UnsetValue || string.IsNullOrEmpty(v.ToString()))) return Visibility.Collapsed;
        return Visibility.Visible;
    }

编辑:
感谢您的想法,它对我有用!

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //if Detail or Solution is not null,not empty and not UnsetValue than show control 
            if (values.Any(v => v is string && !string.IsNullOrEmpty(v.ToString()))) return Visibility.Visible;
            return Visibility.Collapsed;
        }

最新更新