3

私は小さな 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;
    }
}
4

1 に答える 1

1

コレクションが設定されているときに INotifyCollectionChanged の CollectionChanged をサブスクライブしているようで、コレクションが変更されたときにのみサブスクライブを解除します。

CollectionChanged イベントから unscribing して、FrameworkElement の Unloaded イベントも処理します。

e.OldValue または e.NewValue が null であることを確認していないようです。

依存関係プロパティの代わりに、同じ目的で動作を使用できます。主に私が考えていることと同じです。メリット、デメリットはまだ考えていません。動作と依存関係プロパティについて話している興味深いリンクがいくつかあります: Interactivity.Behavior<T> vs 添付プロパティ

https://web.archive.org/web/20130622113553/http://briannoyes.net/2012/12/20/AttachedBehaviorsVsAttachedPropertiesVsBlendBehaviors.aspx

于 2013-01-25T07:59:19.520 に答える