原理:其實分頁功能的實現大家都清楚,無非就是把一個記錄集通過運算來刷選里面對應頁碼的記錄。
接來下我們再次添加新的代碼
- <Grid>
- <DataGrid Name="dataGrid1" AutoGenerateColumns="False">
- <!--省略N個代碼-->
- </DataGrid>
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="轉到" Margin="5"/>
- <TextBox Name="tbxPageNum" Text="" />
- <TextBlock Text="頁" />
- <Button Content="GO" Click="btnGo_Click"/>
- <Button Name="btnUp" Content="上一頁" VerticalAlignment="Center" Click="btnUp_Click"/>
- <Button Name="btnNext" Content="下一頁" VerticalAlignment="Center" Click="btnNext_Click"/>
- <TextBlock Height="20">
- <TextBlock Text="【共" />
- <TextBlock Name="tbkTotal" Foreground="Red" />
- <TextBlock Text="頁】" />
- <TextBlock Text="【當前" />
- <TextBlock Name="tbkCurrentsize" Foreground="Red" />
- <TextBlock Text="頁】" />
- </TextBlock>
- </StackPanel>
- </Grid>
首先我們先寫個分頁的方法,供上面這些事件調用
后台代碼
- //number表示每個頁面顯示的記錄數 currentSize表示當前顯示頁數
- private void Binding(int number, int currentSize)
- {
- List<Information> infoList = new List<Information>();
- infoList = tbInfo.GetInformationList(); //獲取數據源
- int count = infoList.Count; //獲取記錄總數
- int pageSize = 0; //pageSize表示總頁數
- if (count % number == 0)
- {
- pageSize = count / number;
- }
- else
- {
- pageSize = count / number + 1;
- }
- tbkTotal.Text = pageSize.ToString();
- tbkCurrentsize.Text = currentSize.ToString();
- infoList = infoList.Take(number * currentSize).Skip(number * (currentSize - 1)).ToList(); //刷選第currentSize頁要顯示的記錄集
- dataGrid1.ItemsSource = infoList; //重新綁定dataGrid1
- }
- //分頁方法寫好了 接下來就是響應下一頁,上一頁,和跳轉頁面的事件了
- //先定義一個常量
- const int Num=12; //表示每頁顯示12條記錄
- //上一頁事件
- private void btnUp_Click(object sender, RoutedEventArgs e)
- {
- int currentsize = int.Parse(tbkCurrentsize.Text); //獲取當前頁數
- if (currentsize > 1)
- {
- Binding(Num, currentsize - 1); //調用分頁方法
- }
- }
- //下一頁事件
- private void btnNext_Click(object sender, RoutedEventArgs e)
- {
- int total = int.Parse(tbkTotal.Text); //總頁數
- int currentsize = int.Parse(tbkCurrentsize.Text); //當前頁數
- if (currentsize < total)
- {
- Binding(Num, currentsize + 1); //調用分頁方法
- }
- }
- //跳轉事件
- private void btnGo_Click(object sender, RoutedEventArgs e)
- {
- int pageNum = int.Parse(tbxPageNum.Text);
- int total = int.Parse(tbkTotal.Text); //總頁數
- if (pageNum >= 1 && pageNum <= total)
- {
- Binding(Num, pageNum); //調用分頁方法
- }
- }
- 原文參考 http://blog.csdn.net/sanjiawan/article/details/6785394#
