3
我想實現一個轉換器,以便某些XAML元素只有在ObservableCollection
中有項時纔會出現/消失。如何實現CollectionLengthToVisibility轉換器?
我引用了How to access generic property without knowing the closed generic type,但無法讓它與我的實現一起工作。它構建並部署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;
}
}
這裏是我引用的共混物的轉換器/ XAML
<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>