简体   繁体   English

绑定到集合的最后N个元素

[英]Bind to last N elements of a collection

I use wpf toolkit charts to display some data stored in a ObservableCollection . 我使用wpf工具包图表来显示存储在ObservableCollection一些数据。 When there are more than N items stored in that collection only the last N items should be displayed (I cannot delete any items). 当该集合中存储了N个以上的项目时,仅应显示最后N个项目(我不能删除任何项目)。

XAML XAML

<chartingToolkit:LineSeries DependentValueBinding="{Binding DoubleValue,Converter={StaticResource DoubleValueConverter}}" IndependentValueBinding="{Binding Count}" ItemsSource="{Binding Converter={StaticResource DataSourceConverter}}"/>

DataSourceConverter DataSourceConverter

public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ICollection<object> items = value as ICollection<object>;

        int N = 300;

        if (items != null)
        {
            return items.Skip(Math.Max(0, items.Count - N)).Take(N);
        }
        else
        {
            return value;
        }  
    }

ItemSource is bound to a ObservableCollection containing both "DoubleValue" and "Count". ItemSource绑定到同时包含“ DoubleValue”和“ Count”的ObservableCollection It seems like DataSourceConverter is called only once and not when my ObservableCollection is updated. 似乎DataSourceConverter仅被调用一次,而在我的ObservableCollection更新时则不被调用。

忘记转换器,在viewmodel类中创建一个新属性,该属性将返回最后300个项目(就像您现在在转换器中声明的一样),并绑定到该属性。

You could use an ICollectionView and set a Filter on it. 您可以使用ICollectionView并在其上设置一个Filter。

From your ObservableCollection, create a new CollectionView: 在您的ObservableCollection中,创建一个新的CollectionView:

CollectionView topNItems = (CollectionView) CollectionViewSource.GetDefaultView(myObservableCollection);

Next, create the filter on your CollectionView: 接下来,在CollectionView上创建过滤器:

topNItems.Filter += new FilterEventHandler(ShowOnlyTopNItems);

And finally the filter event: 最后是filter事件:

private void ShowOnlyBargainsFilter(object sender, FilterEventArgs e)
{
    int n = 300;
    int listCount = myObservableCollection.Count;
    int indexOfItem = myObservableCollection.IndexOf(e.Item);
    e.Accepted = (listCount - indexOfItem) < n;
}

Now, bind your chart to the new topNItems instead of to the ObservableCollection. 现在,将图表绑定到新的topNItems而不是ObservableCollection。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM