Silverlight中DataGrid控件动态生成列并结合DataPager进行分页

Silverlight中DataGrid控件动态生成列并结合DataPager进行分页,第1张

概述1、准备一个实体类 using System;using System.Collections.Generic;using System.Linq;using System.Web;/// <summary>///电流数据 的摘要说明/// </summary>public class DL{ public int ID { get; set; }

1、准备一个实体类

using System;using System.Collections.Generic;using System.linq;using System.Web;/// <summary>///电流数据 的摘要说明/// </summary>public class DL{    public int ID { get; set; }    public int 泵站ID { get; set; }    public string 机组编号 { get; set; }    public decimal 电流 { get; set; }    public DateTime 时间 { get; set; }}

 

2、编写一个WebService,名称为:getBZInfo.asmx,提供给Silverlight应用程序使用,getBZInfo.cs文件中的代码如下,很简单就是调用数据库访问类,返回一个实体类集合。

using System;using System.Collections.Generic;using System.linq;using System.Web;using System.Web.Services;using USTC;using System.Data;using System.Text;/// <summary>///getBZInfo 的摘要说明/// </summary>[WebService(namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService]public class getBZInfo : System.Web.Services.WebService{    DMBZ dm = new DMBZ();    public getBZInfo()    {        //如果使用设计的组件,请取消注释以下行         //InitializeComponent();     }    #region 电流数据    /// <summary>    ///获取某个泵站下某个机组的电流数据    /// </summary>    /// <param name="bzID"></param>    /// <param name="jzbh"></param>    /// <returns></returns>    [WebMethod(Description = " 获取某个泵站下某个机组的电流数据")]    public DL[] getDlinfoByBH(string bzID,string jzbh)    {        List<DL> List = new List<DL>();        string sql = "select * FROM 电流数据 where 泵站ID='" + bzID + "' and 机组编号='" + jzbh + "'";        DataSet ds = dm.getsql(sql);        if (ds.tables[0].Rows.Count > 0)        {            for (int i = 0; i < ds.tables[0].Rows.Count; i++)            {                DL item = new DL();                item.泵站ID = int.Parse(bzID);                item.机组编号 = jzbh;                item.电流 = decimal.Parse(ds.tables[0].Rows[i]["电流"].ToString());                item.时间 = DateTime.Parse(ds.tables[0].Rows[i]["时间"].ToString());                //将数据添加到集合中去                List.Add(item);            }        }        return List.ToArray();    }    #endregion}

 

3、编译并生成asp.net项目后,右键getBZInfo.asmx,选择在浏览器中浏览,确保可以访问。


4、在Silverlight项目中添加服务引用,发现并添加上面生成的服务,服务命名为bzService,添加成功以后,修改产生的配置文件:ServiceReferences.ClIEntConfig

 

<configuration>    <system.serviceModel>        <bindings>            <basichttpBinding>                <binding name="getBZInfoSoap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">                    <security mode="None" />                </binding>            </basichttpBinding>        </bindings>        <clIEnt>            <endpoint address="http://localhost:1245/webservice/getBZInfo.asmx"                binding="basichttpBinding" bindingConfiguration="getBZInfoSoap"                contract="bzService.getBZInfoSoap" name="getBZInfoSoap" />        </clIEnt>    </system.serviceModel></configuration>


中的<endpoint address="http://localhost:1245/webservice/getBZInfo.asmx" binding="basichttpBinding" bindingConfiguration="getBZInfoSoap" contract="bzService.getBZInfoSoap" name="getBZInfoSoap" />
中的address修改成项目的相对路径,修改后如下:
<endpoint address="../webservice/getBZInfo.asmx" binding="basichttpBinding" bindingConfiguration="getBZInfoSoap" contract="bzService.getBZInfoSoap" name="getBZInfoSoap" />
 
5、在xaml文件中添加一个DataGrID控件和DataPager控件

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/Expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"    xmlns:local="clr-namespace:spjl1"    xmlns:Primitives="clr-namespace:System.windows.Controls.Primitives;assembly=System.windows.Controls.Data"    mc:Ignorable="d"    x:Class="spjl1.yxjk2" WIDth="820" Height="405" Loaded="UserControl_Loaded">    <UserControl.Resources>        <local:DateTimeConverter x:Key="DateTimeConverter" />        <Style x:Key="DataGrIDheaderStyle" targettype="Primitives:DataGrIDColumnheader">            <Setter Property="HorizontalContentAlignment" Value="Center"></Setter>        </Style>        <Style x:Key="DataGrIDCellStyle" targettype="sdk:DataGrIDCell">            <Setter Property="HorizontalContentAlignment" Value="Center" ></Setter>        </Style>    </UserControl.Resources>    <GrID x:name="LayoutRoot">       <sdk:DataGrID x:name="DataGrID1" autoGenerateColumns="False" LoadingRow="DataGrID1_LoadingRow">       </sdk:DataGrID>       <sdk:DataPager x:name="DataPager1" PageSize="6" displayMode="FirstLastPrevIoUsNext" PageIndexChanged="DataPager1_PageIndexChanged"  Height="20" VerticalAlignment="Bottom" d:LayoutOverrIDes="WIDth"/>    </GrID></UserControl>

6、添加一个时间转换类DateTimeConverter.cs文件

using System;using System.Net;using System.windows;using System.windows.Controls;using System.windows.documents;using System.windows.Ink;using System.windows.input;using System.windows.Media;using System.windows.Media.Animation;using System.windows.Shapes;using System.Globalization;using System.windows.Data;namespace spjl1{    #region 为日期定义转换器    //定义一个转换类 并被页面引用为资源      /*    * IValueConverter - 值转换接口,将一个类型的值转换为另一个类型的值。它提供了一种将自定义逻辑应用于绑定的方式    *     Convert - 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法    *     ConvertBack - 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法   */    /// <summary>      /// 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法      /// </summary>      /// <param name="value">转换之前的值</param>      /// <param name="targettype">转换之后的类型</param>      /// <param name="parameter">转换器所使用的参数</param>      /// <param name="culture">转换器所使用的区域信息</param>      /// <returns>转换后的值</returns>      public class DateTimeConverter : IValueConverter    {        public object Convert(object value,Type targettype,object parameter,CultureInfo culture)        {            DateTime date = (DateTime)value;            return date.ToString("yyyy-MM-dd HH:mm:ss");        }        /// <summary>          /// 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法          /// </summary>          /// <param name="value">转换之前的值</param>          /// <param name="targettype">转换之后的类型</param>          /// <param name="parameter">转换器所使用的参数</param>          /// <param name="culture">转换器所使用的区域信息</param>          /// <returns>转换后的值</returns>          public object ConvertBack(object value,CultureInfo culture)        {            string strValue = value.ToString();            DateTime resultDateTime;            if (DateTime.TryParse(strValue,out resultDateTime))            {                return resultDateTime;            }            return value;        }    }    #endregion} 

7、在xaml.cs文件中添加代码并绑定数据,这里增加一个功能就是没1分钟刷新显示一次实时数据,使用dispatcherTimer来实现。

using System.windows.documents;using System.windows.Ink;using System.windows.input;using System.windows.Media;using System.windows.Media.Animation;using System.windows.Shapes;using System.windows.Threading;using spjl1.bzService;using System.Collections.ObjectModel;using System.windows.Data;using System.Text;using System.windows.Markup;namespace spjl1{    public partial class yxjk2 : UserControl    {       public yxjk2()        {            InitializeComponent();        }         private voID UserControl_Loaded(object sender,RoutedEventArgs e)        {            //每一分钟更新一次数据            dispatcherTimer timer = new dispatcherTimer();            timer.Interval = TimeSpan.FromSeconds(60);            timer.Tick += new EventHandler(timer_Tick);            timer.Start();        }        voID timer_Tick(object sender,EventArgs e)        {             //清空数据及分页控件源             this.DataGrID1.ItemsSource = null;             this.DataGrID1.Columns.Clear();             this.DataPager1.source = null;             //加载电流数据            getBZInfoSoapClIEnt clIEnt = new getBZInfoSoapClIEnt();            clIEnt.getDlinfoByBHCompleted += new EventHandler<getDlinfoByBHCompletedEventArgs>(clIEnt_getDlinfoByBHCompleted);            clIEnt.getDlinfoByBHAsync(bzID,jzbh); //这里的2个值是根据实际来赋值的        }       voID clIEnt_getDlinfoByBHCompleted(object sender,getDlinfoByBHCompletedEventArgs e)        {            ObservableCollection<DL> result = e.Result;            //动态生成列            this.DataGrID1.Columns.Add(CreateDataGrIDTextColumn("电流","电流(安培)",180));            this.DataGrID1.Columns.Add(CreateDateTimeTemplate("时间","时间",400));            PagedCollectionVIEw itemListVIEw = new PagedCollectionVIEw(result);            this.DataGrID1.ItemsSource = itemListVIEw;            this.DataPager1.source = itemListVIEw;        }        #region 动态生列方法        /// <summary>        /// 产生模板列(带格式化时间)        /// </summary>        /// <param name="headername"></param>        /// <param name="bindingname"></param>        /// <param name="wIDth"></param>        /// <returns></returns>        public DataGrIDTemplateColumn CreateDateTimeTemplate(string headername,string bindingname,double wIDth)        {            DataGrIDTemplateColumn templateColumn = new DataGrIDTemplateColumn();            templateColumn.header = headername;            StringBuilder CellTemp = new StringBuilder();            CellTemp.Append("<DataTemplate ");            CellTemp.Append("xmlns='http://schemas.microsoft.com/winfx/");            CellTemp.Append("2006/xaml/presentation' ");            CellTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");            CellTemp.Append("xmlns:local='clr-namespace:spjl1");            CellTemp.Append(";assembly=spjl1'>");            CellTemp.Append("<GrID>");            CellTemp.Append("<GrID.Resources>");            CellTemp.Append("<local:DateTimeConverter x:Key='DateTimeConverter' />");            CellTemp.Append("</GrID.Resources>");            CellTemp.Append("<TextBlock ");            CellTemp.Append("Text = '{Binding " + bindingname + ",");            CellTemp.Append("Converter={StaticResource DateTimeConverter}}' ");            CellTemp.Append("margin='4'/>");            CellTemp.Append("</GrID>");            CellTemp.Append("</DataTemplate>");            templateColumn.CellTemplate = (DataTemplate)XamlReader.Load(CellTemp.ToString());            templateColumn.headerStyle = (Style)Resources["DataGrIDheaderStyle"];            templateColumn.CellStyle = (Style)Resources["DataGrIDCellStyle"];            templateColumn.CanUserSort = true;            templateColumn.IsReadonly = true;            templateColumn.WIDth = new DataGrIDLength(wIDth);            return templateColumn;        }        /// <summary>        /// 创建DataGrIDTextColumn模板列        /// </summary>        /// <param name="columnBindname">需要绑定的字段名</param>        /// <param name="columnheadername">模板列的header</param>        /// <param name="wIDth">模板列的宽度</param>        /// <returns></returns>        public DataGrIDTextColumn CreateDataGrIDTextColumn(string columnBindname,string columnheadername,double wIDth)        {            DataGrIDTextColumn dgtextColumn = new DataGrIDTextColumn();            dgtextColumn.Binding = new Binding(columnBindname);            dgtextColumn.header = columnheadername;            dgtextColumn.headerStyle = (Style)Resources["DataGrIDheaderStyle"];            dgtextColumn.CellStyle = (Style)Resources["DataGrIDCellStyle"];            dgtextColumn.IsReadonly = true;            dgtextColumn.WIDth = new DataGrIDLength(wIDth);            return dgtextColumn;        }        #endregion    }}

 

8、最终产生的局部效果图如下:

总结

以上是内存溢出为你收集整理的Silverlight中DataGrid控件动态生成列并结合DataPager进行分页全部内容,希望文章能够帮你解决Silverlight中DataGrid控件动态生成列并结合DataPager进行分页所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1073767.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存