我的应用程序中有一个ObservableCollection<T>
,可以包含大量项目。具体而言,这是来自可能广泛的记录器的摘要信息。我想做的是将此集合的前三项严格绑定到WPF ListView
。
是否有XAML语法或在我的VM中创建辅助属性的简单方法,始终返回集合中的前3项以及更新对集合的任何更改,因为正常ObservableCollection<T>
会如果你正在与完整的清单互动?
答案 0 :(得分:3)
您可以使用返回热门商品的属性推出自己的ObservableCollection<T>
。
这是一个例子,
代码:
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>
答案 1 :(得分:3)
你想检查一下: INotifyPropertyChanged for Count property in WPF?
只需听一下你的ObservableCollection的CollectionChanged
,然后通知你的viewmodel关于更改你的属性只保留前3项(可以简单地实现
public MyTopItems
{
get
{
return myCollection.Take(3);
}
}
答案 2 :(得分:0)
您还可以使用分页列表
return myCollection.Skip(10).Take(3);