WPF Listview排序及分頁(yè)怎么實(shí)現(xiàn)

小億
202
2023-10-22 04:09:50

在WPF中,要實(shí)現(xiàn)ListView的排序和分頁(yè)功能,可以按照以下步驟進(jìn)行操作:

  1. 添加ListView控件到XAML文件中:
<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>
  1. 在ViewModel中創(chuàng)建Items屬性用于綁定ListView的ItemsSource,以及SelectedItem屬性用于綁定ListView的SelectedItem。
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));
    }
}
  1. 在ViewModel中添加排序和分頁(yè)的方法:
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();
}
  1. 在ViewModel的構(gòu)造函數(shù)中初始化Items屬性,并根據(jù)需要進(jìn)行排序和分頁(yè):
public ViewModel()
{
    // 初始化Items屬性

    Sort("Name", ListSortDirection.Ascending); // 按照Name列升序排序
    Page(0, 10); // 默認(rèn)顯示第一頁(yè),每頁(yè)顯示10條記錄
}

通過(guò)以上步驟,就可以在WPF中實(shí)現(xiàn)ListView的排序和分頁(yè)功能??梢愿鶕?jù)實(shí)際需求,在ViewModel中提供排序和分頁(yè)的方法,并在XAML中綁定相關(guān)的命令來(lái)觸發(fā)這些方法。

0