15

我在 WPF、.NET 4.0 中的 DataGrid 控件上绑定 ICollectionView 的属性类型。

Filter使用ICollectionView.

    public ICollectionView CallsView
    {
        get
        {
            return _callsView;
        }
        set
        {
            _callsView = value;
            NotifyOfPropertyChange(() => CallsView);
        }
    }

    private void FilterCalls()
    {
        if (CallsView != null)
        {
            CallsView.Filter = new Predicate<object>(FilterOut);
            CallsView.Refresh();
        }
    }

    private bool FilterOut(object item)
    {
       //..
    }

初始化 ICollection 视图:

IList<Call> source;
CallsView = CollectionViewSource.GetDefaultView(source);

我正在尝试解决这个问题:

例如,源数据计数为 1000 项。我使用过滤器,在 DataGrid 控件中我只显示 200 个项目。

我想将ICollection当前视图转换为IList<Call>

4

4 回答 4

26

你可以试试:

List<Call> CallsList = CallsView.Cast<Call>().ToList();
于 2014-01-08T08:11:09.733 回答
1

因为System.Component.ICollectionView没有实现 IList,所以不能只调用 ToList()。就像 Niloo 已经回答的那样,您首先需要在集合视图中投射项目。

您可以使用以下扩展方法:

/// <summary>
/// Casts a System.ComponentModel.ICollectionView of as a System.Collections.Generic.List&lt;T&gt; of the specified type.
/// </summary>
/// <typeparam name="TResult">The type to cast the elements of <paramref name="source"/> to.</typeparam>
/// <param name="source">The System.ComponentModel.ICollectionView that needs to be casted to a System.Collections.Generic.List&lt;T&gt; of the specified type.</param>
/// <returns>A System.Collections.Generic.List&lt;T&gt; that contains each element of the <paramref name="source"/>
/// sequence cast to the specified type.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
/// <exception cref="InvalidCastException">An element in the sequence cannot be cast to the type <typeparamref name="TResult"/>.</exception>
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Method is provided for convenience.")]
public static List<TResult> AsList<TResult>(this ICollectionView source)
{
    return source.Cast<TResult>().ToList();
}

用法:

var collectionViewList = MyCollectionViewSource.View.AsList<Call>();
于 2014-04-09T10:01:47.337 回答
1

我刚刚在 Silverlight 中遇到了这个问题,但它在 WPF 中是一样的:

IEnumerable<call> calls = collectionViewSource.View.Cast<call>();

于 2013-01-29T04:35:33.127 回答
0

你可以只使用扩展方法来转换:

IList<Call> source = collection.ToList();
于 2012-03-01T11:18:44.477 回答