一个wpf的数据分页控件

来源:互联网 发布:jsp二手交易源码 编辑:程序博客网 时间:2024/06/04 18:52

DataPager 分页控件

代码下载地址:http://download.csdn.net/detail/w_wang_w/8473825

cs部分

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Common.Controls
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:Common.Controls"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根
    /// 元素中:
    ///
    ///     xmlns:MyNamespace="clr-namespace:Common.Controls.DataPage;assembly=Common.Controls.DataPage"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用,
    /// 并重新生成以避免编译错误:
    ///
    ///     在解决方案资源管理器中右击目标项目,然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:CustomControl1/>
    ///
    /// </summary>
    ///
    //定义一委托类型  
    public delegate IEnumerable PageChangeEventHandler(int pageIndex, int pageSize);
    public delegate int CountEventHandler();

    [TemplatePart(Name = PART_BtnJump, Type = typeof(Button))]
    public class DataPager : Control,INotifyPropertyChanged
    {
        #region 构造函数
        static DataPager()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DataPager), new FrameworkPropertyMetadata(typeof(DataPager)));
        }

        public DataPager()
        {
          //  Keyboard.AddKeyDownHandler(this, OnKeyDown);
          //  Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OnMouseDownOutsideCapturedElement);
            this.Loaded += DataPager_Loaded;
          
           
        }
        #endregion

        #region 私有变量

        private const string PART_BtnJump = "PART_BtnJump";
        private const string PART_BtnPrePage = "PART_BtnPrePage";
        private const string PART_BtnNextPage = "PART_BtnNextPage";
        private const string PART_LblPageIndex = "PART_LblPageIndex";
        private const string PART_LblPageCount = "PART_LblPageCount";
        private const string PART_BtnJumpOK = "PART_BtnJumpOK";
        private const string PART_TxtPageIndex = "PART_TxtPageIndex";
       
       

        private ToggleButton btnJump;
        private Button btnPrePage;
        private Button btnNextPage;

        private Label lblPageIndex;
        private Label lblPageCount;

        private Button btnJumpOK;
        private TextBox txtPageIndex;

      
        private IEnumerable m_curPageData;
       

        #endregion

      

        #region  依赖属性
        public static readonly DependencyProperty IsVisablePopupJumpProperty = DependencyProperty.Register("IsVisablePopupJump", typeof(bool), typeof(DataPager), new UIPropertyMetadata(false, null));

        /// <summary>
        /// 依赖属性:单页最大数据量
        /// </summary>
        public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(int), typeof(DataPager), new PropertyMetadata(new PropertyChangedCallback(DataPager.PageSizeChanged)));

        /// <summary>
        /// 每一页的数据数量
        /// </summary>
        public int PageSize
        {
            get
            {
                return (int)GetValue(PageSizeProperty);
            }
            set
            {
                SetValue(PageSizeProperty, value);

            }
        }
        private static void PageSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

        }
       
        #endregion

        #region 属性
        public bool IsVisablePopupJump
        {
            get
            {
                return (bool)GetValue(IsVisablePopupJumpProperty);
            }
            set
            {
                SetValue(IsVisablePopupJumpProperty, value);
            }
        }

        private int pageIndex = 1;
        /// <summary>       
        /// 当前页面索引       
        /// </summary>       
        public int PageIndex
        {
            get
            {
                return pageIndex;
            }
            set
            {
                if (pageIndex != value)
                {
                    pageIndex = value;
                    //RaisePropertyChanged("PageIndex");
                }
               // GotoPage(m_pageIndex);

            }
        }

        private int count;

        /// <summary>
        /// 记录总数
        /// </summary>
        protected int Count
        {
            get
            {
                return count;
            }
            set
            {
                if (count != value)
                {
                    count = value;
                  //  RaisePropertyChanged("Count");
                }
            }
        }

        private int pageCount ;

        /// <summary>
        /// 页数
        /// </summary>
        protected int PageCount
        {
            get
            {
                return pageCount;
            }
            set
            {
                if (pageCount != value)
                {
                    pageCount = value;
                   // RaisePropertyChanged("PageCount");
                }
            }
        }

        /// <summary>
        /// 当前页的数据
        /// </summary>
        public IEnumerable CurPageData
        {
            get
            {
                return m_curPageData;
            }
            set
            {
                if (m_curPageData != value)
                {
                    m_curPageData = value;
                    RaisePropertyChanged("CurPageData");
                }
            }
        }

        #endregion

        #region 事件
        public event PageChangeEventHandler PageChangeEvent;

        public event CountEventHandler CountEvent;

        //计算总记录数,总页数,第一页数据
     


        #endregion

        #region 私有函数
        private void DataPager_Loaded(object sender, RoutedEventArgs e)
        {
            btnJump.IsChecked = false;
            btnJump.Click -= new RoutedEventHandler(btnJump_Click); 
            btnJump.Click += new RoutedEventHandler(btnJump_Click);
            btnPrePage.Click -= new RoutedEventHandler(btnPrePage_Click);
            btnPrePage.Click += new RoutedEventHandler(btnPrePage_Click);

            btnNextPage.Click -= new RoutedEventHandler(btnNextPage_Click);
            btnNextPage.Click += new RoutedEventHandler(btnNextPage_Click);

            btnJumpOK.Click -= new RoutedEventHandler(btnJumpOK_Click);
            btnJumpOK.Click += new RoutedEventHandler(btnJumpOK_Click);

            txtPageIndex.PreviewKeyDown -= new KeyEventHandler(txtPageIndex_PreviewKeyDown);
            txtPageIndex.PreviewKeyDown += new KeyEventHandler(txtPageIndex_PreviewKeyDown);

            InitCountAndPageCount();
            if (Count > 0) PageIndex = 1;
            lblPageIndex.Content = PageIndex.ToString();
            btnPrePage.Visibility = System.Windows.Visibility.Collapsed;
            CurPageData = PageChangeEvent.Invoke(PageIndex, PageSize);
        }

        private void btnJump_Click(object sender, RoutedEventArgs e)
        {
            IsVisablePopupJump = !IsVisablePopupJump;                       
        }

        private void InitCountAndPageCount()
        {
            Count = CountEvent.Invoke();
            int tempvalue = Count % PageSize;
            if (tempvalue == 0)
            {
                PageCount = Count / PageSize;
            }
            else
            {
                PageCount = Count / PageSize + 1;
            }
            lblPageCount.Content = PageCount.ToString();
        }

        private void InitButtonVisibility()
        {
            if (PageIndex > 1)
            {
                btnPrePage.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                btnPrePage.Visibility = System.Windows.Visibility.Collapsed;
            }
            if (PageIndex < PageCount)
            {
                btnNextPage.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                btnNextPage.Visibility = System.Windows.Visibility.Collapsed;
            }

        }

        private void btnPrePage_Click(object sender,RoutedEventArgs e)
        {
            InitCountAndPageCount();
            if ((PageIndex > 1)&&(PageChangeEvent!=null))
            {
                PageIndex = PageIndex - 1;               
                lblPageIndex.Content = PageIndex.ToString();
                CurPageData = PageChangeEvent.Invoke(PageIndex, PageSize);
                InitButtonVisibility();
            }
        }

        private void btnNextPage_Click(object sender, RoutedEventArgs e)
        {
            InitCountAndPageCount();
            if ((PageIndex < PageCount)&&(PageChangeEvent!=null))
            {
                PageIndex = PageIndex + 1;              
                lblPageIndex.Content = PageIndex.ToString();
                CurPageData = PageChangeEvent.Invoke(PageIndex, PageSize);
                InitButtonVisibility();
            }
           
        }

        private void btnJumpOK_Click(object sender, RoutedEventArgs e)
        {
            InitCountAndPageCount();
            try
            {
                PageIndex = int.Parse(txtPageIndex.Text);
                if (PageIndex < 1) PageIndex = 1;
                if (PageIndex > PageCount) PageIndex = PageCount;
                txtPageIndex.Text = PageIndex.ToString();
            }
            catch
            {
                txtPageIndex.Text = string.Empty;
                return;
            }
          
            lblPageIndex.Content = PageIndex.ToString();
            CurPageData = PageChangeEvent.Invoke(PageIndex, PageSize);
            InitButtonVisibility();
          

            IsVisablePopupJump = false;     
        }

        private void txtPageIndex_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                bool shiftKey = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
                bool retVal =false;
                Key key = e.Key;
                //按住shift键后,数字键并不是数字键
                if (key >= Key.D0 && key <= Key.D9 && !shiftKey)
                {
                    retVal = true;
                }              
                if ((key==Key.Delete)||(key==Key.Back))
                {
                    retVal = true;
                }              
                e.Handled = !retVal;
            }
            catch
            {
                e.Handled = true;
            }
        }

        #endregion

        #region 重写函数
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            btnJump = GetTemplateChild(PART_BtnJump) as ToggleButton;
            btnPrePage = GetTemplateChild(PART_BtnPrePage) as Button;
            btnNextPage = GetTemplateChild(PART_BtnNextPage) as Button;
            lblPageIndex = GetTemplateChild(PART_LblPageIndex) as Label;
            lblPageCount = GetTemplateChild(PART_LblPageCount) as Label;
            btnJumpOK = GetTemplateChild(PART_BtnJumpOK) as Button;

            txtPageIndex = GetTemplateChild(PART_TxtPageIndex) as TextBox;

        }
        #endregion

        #region PropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(params string[] propertyNames)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                foreach (string param in propertyNames)
                {
                    handler(this, new PropertyChangedEventArgs(param));
                }

            }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}

 

Themes/Generic.xaml 部分


    <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Common.Controls">

  
    <Style x:Key="LinkButton" TargetType="Button">
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <TextBlock >
                           <ContentPresenter />
                    </TextBlock>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Foreground" Value="Blue" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Foreground" Value="Red" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="LinkToggleButton" TargetType="ToggleButton">
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <TextBlock >
                           <ContentPresenter />
                    </TextBlock>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Foreground" Value="Blue" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Foreground" Value="Red" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="{x:Type local:DataPager}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:DataPager}">
                    <Border x:Name="PART_Border" Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="10,0,5,0" HorizontalAlignment="Right">
                            <Label x:Name="PART_LblPageIndex" Content=""></Label>
                            <Label Content="/"></Label>
                            <Label x:Name="PART_LblPageCount" Content=""></Label>
                            <Button x:Name="PART_BtnPrePage" Style="{StaticResource LinkButton}" Margin="5" Content="上一页" Cursor="Hand"/>
                            <Button x:Name="PART_BtnNextPage" Style="{StaticResource LinkButton}" Margin="5" Content="下一页" Cursor="Hand"/>
                            <ToggleButton x:Name="PART_BtnJump" Style="{StaticResource LinkToggleButton}"  Margin="5" Content="跳转" Cursor="Hand"/>
                            <Popup x:Name="PART_PopupJump" PlacementTarget="{Binding ElementName=PART_BtnJump}"                                  
                           Width="150"                                 
                           AllowsTransparency="True"
                           StaysOpen="False"
                           Placement="Top" HorizontalAlignment="Left" HorizontalOffset="-120"                                  
                           Focusable="False"
                           IsOpen="{Binding IsChecked,ElementName=PART_BtnJump}"  >
                                <Border BorderThickness="1" BorderBrush="Blue" Background="White"  HorizontalAlignment="Stretch"  Width="{TemplateBinding Width}">
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition></RowDefinition>

                                        </Grid.RowDefinitions>
                                        <StackPanel Width="{TemplateBinding Width}" Orientation="Horizontal">
                                            <Label Content="跳转到第"></Label>
                                            <TextBox x:Name="PART_TxtPageIndex" Width="30"></TextBox>
                                            <Label Content="页"></Label>
                                            <Button x:Name="PART_BtnJumpOK" Content="确定"></Button>
                                        </StackPanel>

                                    </Grid>
                                </Border>
                            </Popup>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

   
</ResourceDictionary>

 

 

控件的调用:

.xaml

<DataGrid Height="170" ItemsSource="{Binding Path=CurPageData,ElementName=Pager}" HorizontalAlignment="Left" Margin="10,26,0,0" VerticalAlignment="Top" RenderTransformOrigin="-6.417,-2.538"/>
        <Controls:DataPager x:Name="Pager"  HorizontalAlignment="Left" Height="27" Margin="137,202,0,0" VerticalAlignment="Top" Width="193" PageSize="10"   PageChangeEvent="DataPager_PageChangeEvent" CountEvent="DataPager_CountEvent" />

 

.cs

private System.Collections.IEnumerable DataPager_PageChangeEvent(int pageIndex, int pageSize)
        {
            //自己实现分页数据查询
            return (System.Collections.IEnumerable)ExampleBLL.Example1BLL.GetTable1Data(pageIndex, pageSize);
        }

        private int DataPager_CountEvent()
        {

         //自己实现获取数据总数事件
            return ExampleBLL.Example1BLL.GetTable1Count();
        }

 

0 0