绑定到ListView的ObservableCollection中的前N个项目 [英] Binding to first N items in an ObservableCollection on a ListView
问题描述
我的应用程序中有一个ObservableCollection<T>
,可以容纳许多物品.具体来说,这是来自潜在的大量记录器的摘要信息.我想做的就是将这个集合的前三项严格绑定到WPF ListView
.
I have an ObservableCollection<T>
in my application that can hold numerous items. Specifically, this is summary information from a potentially extensive logger. What I'd like to do is bind strictly the top 3 items of this collection to WPF ListView
.
是否存在XAML语法,或者是一种简单的方法来在我的VM中创建辅助属性,以便始终返回集合中的前3个项目,并像正常的ObservableCollection<T>
一样更新集合的所有更改(如果您正在与完整列表进行交互?
Is there XAML syntax, or a simple enough way to create a secondary property in my VM, to always return the top 3 items in the collection as well as update any changes to the collection as a normal ObservableCollection<T>
would if you were interacting with a complete list?
推荐答案
您可以推出自己的ObservableCollection<T>
,该属性会返回热门项目.
You could roll-out your own ObservableCollection<T>
with a property returning top items.
这是一个例子,
代码:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow
{
public MyCollection Collection { get; }
public MainWindow()
{
InitializeComponent();
Collection = new MyCollection();
DataContext = Collection;
}
private void button_Click(object sender, RoutedEventArgs e)
{
Collection.Add(Collection.Count);
}
}
public sealed class MyCollection : ObservableCollection<int>
{
public MyCollection()
{
CollectionChanged += MyCollection_CollectionChanged;
}
private void MyCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{ // to notify XAML-side binding
OnPropertyChanged(new PropertyChangedEventArgs(nameof(TopItems)));
}
public IEnumerable<int> TopItems => this.Take(3);
}
}
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
d:DataContext="{d:DesignInstance local:MyCollection}"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Click="button_Click" Content="Button" />
<ListBox Grid.Row="1" ItemsSource="{Binding}" />
<ListBox Grid.Row="2" ItemsSource="{Binding TopItems}" />
</Grid>
</Window>
这篇关于绑定到ListView的ObservableCollection中的前N个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!