我一直在编写一个小的 Silverlight 帮助器类来实现一个附加属性,该属性可以绑定到ICollection
/INotifyCollectionChanged
并在绑定集合为空时切换目标对象的可见性。
我没有完全掌握DependencyProperty
有关内存管理和对象生命周期的行为。
这是来源:
public class DisplayOnCollectionEmpty : DependencyObject
{
#region Constructor and Static Constructor
/// <summary>
/// This is not a constructable class, but it cannot be static because
/// it derives from DependencyObject.
/// </summary>
private DisplayOnCollectionEmpty()
{
}
#endregion
public static object GetCollection(DependencyObject obj)
{
return (object)obj.GetValue(CollectionProperty);
}
public static void SetCollection(DependencyObject obj, object value)
{
obj.SetValue(CollectionProperty, value);
}
// Using a DependencyProperty as the backing store for Collection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CollectionProperty =
DependencyProperty.RegisterAttached("Collection", typeof(object), typeof(FrameworkElement), new PropertyMetadata(OnCollectionPropertyChanged));
private static void OnCollectionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement fe = d as FrameworkElement;
NotifyCollectionChangedEventHandler onCollectionChanged = (sender, collectionChangedEventArgs) =>
{
fe.Visibility = GetVisibility(e.NewValue as ICollection);
};
if (e.OldValue is INotifyCollectionChanged)
{
((INotifyCollectionChanged)e.OldValue).CollectionChanged -= onCollectionChanged;
}
if (e.NewValue is INotifyCollectionChanged)
{
((INotifyCollectionChanged)e.NewValue).CollectionChanged += onCollectionChanged;
}
fe.Visibility = GetVisibility(e.NewValue as ICollection);
}
private static Visibility GetVisibility(ICollection collection)
{
if (collection == null) return Visibility.Visible;
return collection.Count < 1 ? Visibility.Visible : Visibility.Collapsed;
}
}