WPF分页代码
以下是WPF分页代码的示例:
XAML代码:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Name="listBox" Grid.Row="0" Margin="10"/>
<StackPanel Name="pagination" Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="10">
<Button Name="btnPrev" Content="Prev" Click="BtnPrev_Click"/>
<Label Name="lblPageNumber" Content="Page 1"/>
<Button Name="btnNext" Content="Next" Click="BtnNext_Click"/>
</StackPanel>
</Grid>
C#代码:
public partial class MainWindow : Window
{
private const int PageSize = 10; // 每页显示的数量
private int _currentPage = 1; // 当前页码
private int _totalPages; // 总页数
private List<string> _items; // 假数据
public MainWindow()
{
InitializeComponent();
_items = Enumerable.Range(1, 100).Select(i => $"Item {i}").ToList();
UpdateList();
}
private void UpdateList()
{
var startIndex = (CurrentPage - 1) * PageSize;
var items = _items.Skip(startIndex).Take(PageSize).ToList();
listBox.ItemsSource = items;
UpdatePagination();
}
private void UpdatePagination()
{
var totalCount = _items.Count;
_totalPages = (int)Math.Ceiling(totalCount / (double)PageSize);
lblPageNumber.Content = $"Page {_currentPage}/{_totalPages}";
btnPrev.IsEnabled = _currentPage > 1;
btnNext.IsEnabled = _currentPage < _totalPages;
}
private void BtnPrev_Click(object sender, RoutedEventArgs e)
{
if (_currentPage > 1)
{
_currentPage--;
UpdateList();
}
}
private void BtnNext_Click(object sender, RoutedEventArgs e)
{
if (_currentPage < _totalPages)
{
_currentPage++;
UpdateList();
}
}
private int CurrentPage
{
get { return _currentPage; }
set
{
_currentPage = value;
UpdateList();
}
}
}
这个示例中,我们使用ListBox来显示数据,使用StackPanel来显示分页器。我们还定义了每页显示的数量,并使用假数据来填充ListBox。在UpdateList方法中,我们使用Skip和Take方法来获取当前页的数据,并将其设置为ListBox的数据源。在UpdatePagination方法中,我们计算总页数,并更新页码和按钮状态。在BtnPrev_Click和BtnNext_Click方法中,我们通过增加或减少当前页码来更新列表。最后,我们定义了一个名为CurrentPage的属性,它在设置值时会自动调用UpdateList方法来更新列表。
原文地址: https://www.cveoy.top/t/topic/bDmg 著作权归作者所有。请勿转载和采集!