如何将WPF CollectionViewGroup类型更改为自定义类型并在ListCollectionView中使用它

时间:2014-03-12 04:20:49

标签: c# wpf collectionviewsource

如何将View属性的类型覆盖为我的自定义类型。 我的CustomGroupListCollectionView类型为Groups属性添加了额外的属性。 在运行时,当我观察View属性的类型是ListCollectionView时,我想将其更改为CustomGroupListCollectionView。

public class CollectionViewSourceCustom : CollectionViewSource
{
    public new  CustomGroupListCollectionView View { get; set; }
}

public class CustomGroupListCollectionView : ListCollectionView
{
    private readonly CustomGroup _allGroup;

    public CustomGroupListCollectionView(IList list)
        : base(list)
    {
        _allGroup = new CustomGroup("All");
        foreach (var item in list)
        {
            _allGroup.AddItem(item);
        }
    }

    public override ReadOnlyObservableCollection<object> Groups
    {
        get
        {
            var group = new ObservableCollection<object>(base.Groups.ToList());
            group.Add(_allGroup);
            return new ReadOnlyObservableCollection<object>(group);
        }
    }
}

public class CustomGroup : CollectionViewGroup
{
    public CustomGroup(object name)
        : base(name)
    {
    }

    public void AddItem(object item)
    {
        ProtectedItems.Add(item);
    }

    public override bool IsBottomLevel
    {
        get { return true; }
    }

    bool _IsChecked;
    public bool IsChecked
    {
        get { return _IsChecked; }
        set { _IsChecked = value; }
    }
    Visibility _CheckBoxVisibility;
    public Visibility CheckBoxVisibility
    {
        get { return _CheckBoxVisibility; }
        set { _CheckBoxVisibility = value; }
    }

    bool _IsExpanded;
    public bool IsExpanded
    {
        get { return _IsExpanded; }
        set { _IsExpanded = value; }
    }
    Visibility _ExpanderVisibility;
    public Visibility ExpanderVisibility
    {
        get { return _ExpanderVisibility; }
        set { _ExpanderVisibility = value; }
    }

    Visibility _ImageVisibility = Visibility.Collapsed;
    public Visibility ImageVisibility
    {
        get { return _ImageVisibility; }
        set { _ImageVisibility = value; }
    }
} 

2 个答案:

答案 0 :(得分:5)

CollectionViewSource有一个CollectionViewType属性,您可以使用它来确定CollectionViewSource返回的CollectionView的类型,例如

<CollectionViewSource x:Key="source" CollectionViewType="{x:Type my:CustomGroupListCollectionView}" Source="{Binding MyData}"/>

如您所见,您甚至不必创建新的CollectionViewSource类。

答案 1 :(得分:2)

如果您仍坚持使用自己的方式,我会建议使用以下代码:

public class CollectionViewSourceCustom : CollectionViewSource
{
    public CollectionViewSourceCustom()
        : base()
    {
        ((ISupportInitialize)this).BeginInit();

        this.CollectionViewType = typeof(CustomGroupListCollectionView);

        ((ISupportInitialize)this).EndInit();
    }
}

希望它有所帮助。