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

1、准备一个实体类

  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Web; 
  5.  
  6. /// <summary> 
  7. ///电流数据 的摘要说明 
  8. /// </summary> 
  9. public class DL 
  10.     public int ID { get; set; } 
  11.     public int 泵站ID { get; set; } 
  12.     public string 机组编号 { get; set; } 
  13.     public decimal 电流 { get; set; } 
  14.     public DateTime 时间 { get; set; } 

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

  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Web; 
  5. using System.Web.Services; 
  6. using USTC; 
  7. using System.Data; 
  8. using System.Text; 
  9.  
  10. /// <summary> 
  11. ///getBZInfo 的摘要说明 
  12. /// </summary> 
  13. [WebService(Namespace = "http://tempuri.org/")] 
  14. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
  15. //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
  16. // [System.Web.Script.Services.ScriptService] 
  17. public class getBZInfo : System.Web.Services.WebService 
  18.     DMBZ dm = new DMBZ(); 
  19.     public getBZInfo() 
  20.     { 
  21.         //如果使用设计的组件,请取消注释以下行  
  22.         //InitializeComponent();  
  23.     } 
  24.     #region 电流数据 
  25.     /// <summary> 
  26.     ///获取某个泵站下某个机组的电流数据 
  27.     /// </summary> 
  28.     /// <param name="bzid"></param> 
  29.     /// <param name="jzbh"></param> 
  30.     /// <returns></returns> 
  31.     [WebMethod(Description = " 获取某个泵站下某个机组的电流数据")] 
  32.     public DL[] getDLInfoByBH(string bzid, string jzbh) 
  33.     { 
  34.         List<DL> list = new List<DL>(); 
  35.         string sql = "select * FROM 电流数据 where 泵站ID='" + bzid + "' and 机组编号='" + jzbh + "'"
  36.         DataSet ds = dm.getsql(sql); 
  37.         if (ds.Tables[0].Rows.Count > 0) 
  38.         { 
  39.             for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
  40.             { 
  41.                 DL item = new DL(); 
  42.                 item.泵站ID = int.Parse(bzid); 
  43.                 item.机组编号 = jzbh; 
  44.                 item.电流 = decimal.Parse(ds.Tables[0].Rows[i]["电流"].ToString()); 
  45.                 item.时间 = DateTime.Parse(ds.Tables[0].Rows[i]["时间"].ToString()); 
  46.                 //将数据添加到集合中去 
  47.                 list.Add(item); 
  48.             } 
  49.         } 
  50.         return list.ToArray(); 
  51.     } 
  52.     #endregion 

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


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

  1. <configuration> 
  2.     <system.serviceModel> 
  3.         <bindings> 
  4.             <basicHttpBinding> 
  5.                 <binding name="getBZInfoSoap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> 
  6.                     <security mode="None" /> 
  7.                 </binding> 
  8.             </basicHttpBinding> 
  9.         </bindings> 
  10.         <client> 
  11.             <endpoint address="http://localhost:1245/webservice/getBZInfo.asmx" 
  12.                 binding="basicHttpBinding" bindingConfiguration="getBZInfoSoap" 
  13.                 contract="bzService.getBZInfoSoap" name="getBZInfoSoap" /> 
  14.         </client> 
  15.     </system.serviceModel> 
  16. </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控件

  1. <UserControl 
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  6.     xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
  7.     xmlns:local="clr-namespace:spjl1" 
  8.     xmlns:Primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data" 
  9.     mc:Ignorable="d" 
  10.     x:Class="spjl1.yxjk2" Width="820" Height="405" Loaded="UserControl_Loaded"> 
  11.     <UserControl.Resources> 
  12.         <local:DateTimeConverter x:Key="DateTimeConverter" /> 
  13.         <Style x:Key="DataGridHeaderStyle" TargetType="Primitives:DataGridColumnHeader"> 
  14.             <Setter Property="HorizontalContentAlignment" Value="Center"></Setter> 
  15.         </Style> 
  16.         <Style x:Key="DataGridCellStyle" TargetType="sdk:DataGridCell"> 
  17.             <Setter Property="HorizontalContentAlignment" Value="Center" ></Setter> 
  18.         </Style> 
  19.     </UserControl.Resources> 
  20.     <Grid x:Name="LayoutRoot"> 
  21.        <sdk:DataGrid x:Name="DataGrid1" AutoGenerateColumns="False" LoadingRow="DataGrid1_LoadingRow"> 
  22.        </sdk:DataGrid> 
  23.        <sdk:DataPager x:Name="DataPager1" PageSize="6" DisplayMode="FirstLastPreviousNext" PageIndexChanged="DataPager1_PageIndexChanged"  Height="20" VerticalAlignment="Bottom" d:LayoutOverrides="Width"/> 
  24.     </Grid> 
  25. </UserControl> 

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

  1. using System; 
  2. using System.Net; 
  3. using System.Windows; 
  4. using System.Windows.Controls; 
  5. using System.Windows.Documents; 
  6. using System.Windows.Ink; 
  7. using System.Windows.Input; 
  8. using System.Windows.Media; 
  9. using System.Windows.Media.Animation; 
  10. using System.Windows.Shapes; 
  11. using System.Globalization; 
  12. using System.Windows.Data; 
  13.  
  14. namespace spjl1 
  15.     #region 为日期定义转换器 
  16.     //定义一个转换类 并被页面引用为资源   
  17.     /*
  18.    * IValueConverter - 值转换接口,将一个类型的值转换为另一个类型的值。它提供了一种将自定义逻辑应用于绑定的方式
  19.    *     Convert - 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法
  20.    *     ConvertBack - 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法
  21.   */ 
  22.     /// <summary>   
  23.     /// 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法   
  24.     /// </summary>   
  25.     /// <param name="value">转换之前的值</param>   
  26.     /// <param name="targetType">转换之后的类型</param>   
  27.     /// <param name="parameter">转换器所使用的参数</param>   
  28.     /// <param name="culture">转换器所使用的区域信息</param>   
  29.     /// <returns>转换后的值</returns>   
  30.     public class DateTimeConverter : IValueConverter 
  31.     { 
  32.         public object Convert(object value, 
  33.                            Type targetType, 
  34.                            object parameter, 
  35.                            CultureInfo culture) 
  36.         { 
  37.             DateTime date = (DateTime)value; 
  38.             return date.ToString("yyyy-MM-dd HH:mm:ss"); 
  39.         } 
  40.         /// <summary>   
  41.         /// 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法   
  42.         /// </summary>   
  43.         /// <param name="value">转换之前的值</param>   
  44.         /// <param name="targetType">转换之后的类型</param>   
  45.         /// <param name="parameter">转换器所使用的参数</param>   
  46.         /// <param name="culture">转换器所使用的区域信息</param>   
  47.         /// <returns>转换后的值</returns>   
  48.         public object ConvertBack(object value, 
  49.                                   Type targetType, 
  50.                                   object parameter, 
  51.                                   CultureInfo culture) 
  52.         { 
  53.             string strValue = value.ToString(); 
  54.             DateTime resultDateTime; 
  55.             if (DateTime.TryParse(strValue, out resultDateTime)) 
  56.             { 
  57.                 return resultDateTime; 
  58.             } 
  59.             return value; 
  60.         } 
  61.     } 
  62.     #endregion 
  63.  
  64.  
  65.   

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

  1. using System.Windows.Documents; 
  2. using System.Windows.Ink; 
  3. using System.Windows.Input; 
  4. using System.Windows.Media; 
  5. using System.Windows.Media.Animation; 
  6. using System.Windows.Shapes; 
  7. using System.Windows.Threading; 
  8. using spjl1.bzService; 
  9. using System.Collections.ObjectModel; 
  10. using System.Windows.Data; 
  11. using System.Text; 
  12. using System.Windows.Markup; 
  13.  
  14. namespace spjl1 
  15.     public partial class yxjk2 : UserControl 
  16.     { 
  17.  
  18.        public yxjk2() 
  19.         { 
  20.             InitializeComponent(); 
  21.  
  22.         } 
  23.  
  24.          private void UserControl_Loaded(object sender, RoutedEventArgs e) 
  25.         { 
  26.             //每一分钟更新一次数据 
  27.             DispatcherTimer timer = new DispatcherTimer(); 
  28.             timer.Interval = TimeSpan.FromSeconds(60); 
  29.             timer.Tick += new EventHandler(timer_Tick); 
  30.             timer.Start(); 
  31.         } 
  32.  
  33.         void timer_Tick(object sender, EventArgs e) 
  34.         { 
  35.  
  36.              //清空数据及分页控件源 
  37.              this.DataGrid1.ItemsSource = null
  38.              this.DataGrid1.Columns.Clear(); 
  39.              this.DataPager1.Source = null
  40.              //加载电流数据 
  41.             getBZInfoSoapClient client = new getBZInfoSoapClient(); 
  42.             client.getDLInfoByBHCompleted += new EventHandler<getDLInfoByBHCompletedEventArgs>(client_getDLInfoByBHCompleted); 
  43.             client.getDLInfoByBHAsync(bzid, jzbh); //这里的2个值是根据实际来赋值的 
  44.  
  45.         } 
  46.  
  47.        void client_getDLInfoByBHCompleted(object sender, getDLInfoByBHCompletedEventArgs e) 
  48.         { 
  49.             ObservableCollection<DL> result = e.Result; 
  50.             //动态生成列 
  51.             this.DataGrid1.Columns.Add(CreateDataGridTextColumn("电流", "电流(安培)", 180)); 
  52.             this.DataGrid1.Columns.Add(CreateDateTimeTemplate("时间", "时间", 400)); 
  53.             PagedCollectionView itemListView = new PagedCollectionView(result); 
  54.             this.DataGrid1.ItemsSource = itemListView
  55.             this.DataPager1.Source = itemListView
  56.         } 
  57.  
  58.         #region 动态生列方法 
  59.         /// <summary> 
  60.         /// 产生模板列(带格式化时间) 
  61.         /// </summary> 
  62.         /// <param name="headername"></param> 
  63.         /// <param name="bindingname"></param> 
  64.         /// <param name="width"></param> 
  65.         /// <returns></returns> 
  66.         public DataGridTemplateColumn CreateDateTimeTemplate(string headername, string bindingname, double width) 
  67.         { 
  68.             DataGridTemplateColumn templateColumn = new DataGridTemplateColumn(); 
  69.             templateColumn.Header = headername
  70.  
  71.             StringBuilder CellTemp = new StringBuilder(); 
  72.  
  73.             CellTemp.Append("<DataTemplate "); 
  74.             CellTemp.Append("xmlns='http://schemas.microsoft.com/winfx/"); 
  75.  
  76.             CellTemp.Append("2006/xaml/presentation' "); 
  77.             CellTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' "); 
  78.  
  79.  
  80.             CellTemp.Append("xmlns:local='clr-namespace:spjl1"); 
  81.             CellTemp.Append(";assembly=spjl1'>"); 
  82.  
  83.             CellTemp.Append("<Grid>"); 
  84.             CellTemp.Append("<Grid.Resources>"); 
  85.  
  86.             CellTemp.Append("<local:DateTimeConverter x:Key='DateTimeConverter' />"); 
  87.             CellTemp.Append("</Grid.Resources>"); 
  88.  
  89.             CellTemp.Append("<TextBlock "); 
  90.             CellTemp.Append("Text = '{Binding " + bindingname + ", "); 
  91.  
  92.             CellTemp.Append("Converter={StaticResource DateTimeConverter}}' "); 
  93.             CellTemp.Append("Margin='4'/>"); 
  94.  
  95.             CellTemp.Append("</Grid>"); 
  96.             CellTemp.Append("</DataTemplate>"); 
  97.  
  98.             templateColumn.CellTemplate = (DataTemplate)XamlReader.Load(CellTemp.ToString()); 
  99.             templateColumn.HeaderStyle = (Style)Resources["DataGridHeaderStyle"]; 
  100.             templateColumn.CellStyle = (Style)Resources["DataGridCellStyle"]; 
  101.             templateColumn.CanUserSort = true
  102.             templateColumn.IsReadOnly = true
  103.             templateColumn.Width = new DataGridLength(width); 
  104.             return templateColumn; 
  105.         } 
  106.  
  107.         /// <summary> 
  108.         /// 创建DataGridTextColumn模板列 
  109.         /// </summary> 
  110.         /// <param name="columnBindName">需要绑定的字段名</param> 
  111.         /// <param name="columnHeaderName">模板列的Header</param> 
  112.         /// <param name="width">模板列的宽度</param> 
  113.         /// <returns></returns> 
  114.         public DataGridTextColumn CreateDataGridTextColumn(string columnBindName, string columnHeaderName, double width) 
  115.         { 
  116.             DataGridTextColumn dgtextColumn = new DataGridTextColumn(); 
  117.             dgtextColumn.Binding = new Binding(columnBindName); 
  118.             dgtextColumn.Header = columnHeaderName
  119.             dgtextColumn.HeaderStyle = (Style)Resources["DataGridHeaderStyle"]; 
  120.             dgtextColumn.CellStyle = (Style)Resources["DataGridCellStyle"]; 
  121.             dgtextColumn.IsReadOnly = true
  122.             dgtextColumn.Width = new DataGridLength(width); 
  123.             return dgtextColumn; 
  124.         } 
  125.         #endregion 
  126.  
  127.     } 
  128.  

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值