我想实现一个转换器,以便某些 XAML 元素仅在ObservableCollection
.
我已经引用了如何在不知道封闭泛型类型的情况下访问泛型属性,但无法使其与我的实现一起使用。它构建和部署 OK(到 Windows Phone 7 模拟器和设备)但不起作用。而且Blend会抛出异常,不再渲染页面,
NullReferenceException:对象引用未设置为对象的实例。
这是我到目前为止所拥有的,
// 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>