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, Type targetType, object parameter, 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、最终产生的局部效果图如下: