c# - 如何实现 CollectionLengthToVisibility 转换器?

标签 c# windows-phone-7 xaml binding

我想实现一个转换器,以便某些 XAML 元素仅在 ObservableCollection 中有项目时才出现/消失。

我引用了 How to access generic property without knowing the closed generic type但无法让它与我的实现一起使用。它构建和部署正常(到 Windows Phone 7 模拟器和设备)但不起作用。此外,Blend 抛出异常,将不再呈现页面,

NullReferenceException: Object reference not set to an instance of an object.

这是我目前的情况,

// Sets the vsibility depending on whether the collection is empty or not depending if parameter is "VisibleOnEmpty" or "CollapsedOnEmpty"
public class CollectionLengthToVisibility : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        // From https://stackoverflow.com/questions/4592644/how-to-access-generic-property-without-knowing-the-closed-generic-type
        var p = value.GetType().GetProperty("Length");
        int? length = p.GetValue(value, new object[] { }) as int?;

        string s = (string)parameter;
        if ( ((length == 0) && (s == "VisibleOnEmpty")) 
            || ((length != 0) && (s == "CollapsedOnEmpty")) )
        {
            return Visibility.Visible;
        }
        else
        {
            return Visibility.Collapsed;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        return null;
    }


}

这是我在 Blend/XAML 上引用转换器的方式

<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>

最佳答案

我会使用 Enumerable.Any()扩展方法。它适用于任何 IEnumerable<T>并避免您必须知道您正在处理的是哪种集合。因为你不知道T你可以只使用 .Cast<object>()

public class CollectionLengthToVisibility : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        var collection = value as System.Collections.IEnumerable;
        if (collection == null)
            throw new ArgumentException("value");

        if (collection.Cast<object>().Any())
               return Visibility.Visible;
        else
               return Visibility.Collapsed;    
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        throw new NotImplementedException();
    }


}

关于c# - 如何实现 CollectionLengthToVisibility 转换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913434/

相关文章:

c# - 如何捕获因USB电缆被拔出而消失的串口

c# - Visual Studio中损坏的Windows窗体

c# - 绑定(bind)更新问题

silverlight - 将自定义字体设置为 Web 浏览器控件,Windows Phone 7/7.5

c# - Windows Phone 中的 XNA RenderTarget2D

c# - 数据绑定(bind) Int 属性到 WPF 中的枚举

wpf - 如何清除 MVVM 中的文本框?

c# - 数字格式在 ASP.NET Core 中不起作用

c# - 未加载本地化资源

c# - 在 Xaml (Xamarin.Forms) 中设置网格行的最小或最大高度