Silverlight中DataGrid控件动态生成列并结合DataPager进行分页
2011-09-16 08:17
507 查看
1、准备一个实体类
view plaincopy to clipboardprint?
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; }
}
3、编译并生成asp.net项目后,右键getBZInfo.asmx,选择在浏览器中浏览,确保可以访问。
4、在Silverlight项目中添加服务引用,发现并添加上面生成的服务,服务命名为bzService,添加成功以后,修改产生的配置文件:ServiceReferences.ClientConfig
view plaincopy to clipboardprint?
<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>
6、添加一个时间转换类DateTimeConverter.cs文件
view plaincopy to clipboardprint?
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,
Type targetType,
object parameter,
CultureInfo culture)
{
string strValue = value.ToString();
DateTime resultDateTime;
if (DateTime.TryParse(strValue,
out resultDateTime))
{
return resultDateTime;
}
return value;
}
}
#endregion
}
8、最终产生的局部效果图如下:
view plaincopy to clipboardprint?
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; }
}
view plaincopy to clipboardprint? 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 } 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
view plaincopy to clipboardprint?
<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>
view plaincopy to clipboardprint? <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> <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文件
view plaincopy to clipboardprint?
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,
Type targetType,
object parameter,
CultureInfo culture)
{
string strValue = value.ToString();
DateTime resultDateTime;
if (DateTime.TryParse(strValue,
out resultDateTime))
{
return resultDateTime;
}
return value;
}
}
#endregion
}
view plaincopy to clipboardprint? 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 } } 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 - 没有RIA Services时使用Data Pager实现服务端数据分页
- Silverlight客户端分页 DataPager控件的使用
- silverlight分页控件DataPager使用要点
- Listview 利用Datapager进行分页
- ListView结合DataPager实现分页的功能(数据绑定时)
- ListView加DataPager在不使用LinqDataSource(DataSourceID)时如何动态分页
- c# winform结合数据库动态生成treeview的父节点和子节点方法和思路
- 利用ListView和DataPager控件来对数据分页
- asp.net2.0 动态生成静态页并分页实例
- 结合smarty,获取$_GET传递过来的参数并进行重新索取和排列,以便传递给分页函数
- 动态生成分页
- ssh中利用pager-taglib和filter进行分页
- lucene.net helper类 【结合盘古分词进行搜索的小例子(分页功能)】
- highchats与php结合生成动态统计图
- innerHTML动态生成table并进行数据填充
- 使用Silverlight3中的DataPager实现服务器端分页[转]
- SqlDataReader生成动态Lambda表达式
- .NET4.0的listview与DataPager的结合使用时的模板编辑
- yii cgridview 对生成的数据进行分页