在WPF中,要實現ListView的排序和分頁功能,可以按照以下步驟進行操作:
<ListView x:Name="listView"
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"
IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="120"/>
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="80"/>
<GridViewColumn Header="Gender" DisplayMemberBinding="{Binding Gender}" Width="80"/>
<!-- 其他列 -->
</GridView>
</ListView.View>
</ListView>
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<Item> _items;
private Item _selectedItem;
public ObservableCollection<Item> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged("Items");
}
}
public Item SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
// 其他屬性和方法
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private void Sort(string propertyName, ListSortDirection sortDirection)
{
ICollectionView view = CollectionViewSource.GetDefaultView(Items);
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription(propertyName, sortDirection));
view.Refresh();
}
private void Page(int pageIndex, int pageSize)
{
ICollectionView view = CollectionViewSource.GetDefaultView(Items);
view.PageSize = pageSize;
view.MoveToPage(pageIndex);
view.Refresh();
}
public ViewModel()
{
// 初始化Items屬性
Sort("Name", ListSortDirection.Ascending); // 按照Name列升序排序
Page(0, 10); // 默認顯示第一頁,每頁顯示10條記錄
}
通過以上步驟,就可以在WPF中實現ListView的排序和分頁功能。可以根據實際需求,在ViewModel中提供排序和分頁的方法,并在XAML中綁定相關的命令來觸發這些方法。