Je souhaite implémenter un convertisseur afin que certains éléments XAML n'apparaissent/disparaissent que s'il y a des éléments dans un ObservableCollection
.Comment implémenter un convertisseur CollectionLengthToVisibility?
J'ai référencé How to access generic property without knowing the closed generic type mais je n'arrive pas à l'utiliser avec ma mise en œuvre. Il construit et déploie OK (pour Windows Phone 7 émulateur et périphérique) mais ne fonctionne pas. De plus Blend jette une exception et ne sera plus rendre la page,
NullReferenceException: objet de référence non définie à une instance d'un objet .
Voici ce que j'ai jusqu'à présent,
// 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;
}
}
Voici comment je référencent convertisseur sur Blend/XAML
<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>