Silverlight调用WebService只能使用异步方式调用。所谓异步方式调用就是让调用方法的主线程不必同步等待在这个函数调用上,从而允许主线程继续执行它下面的代码。
Silverlight调用自定义的WebService分为四个步骤:
(1)、创建自定义的WebService
(2)、实现WebService
(3)、在Silverlight项目中添加服务引用
(4)、使用异步方式调用WebService
下面举例介绍:
比如说在MSsql2000中建立一个名为SilverlightDB的数据库,里面包含一张表Product,里面有2个字段Name和Price,举例说明字段就随便用两个意思意思下。
<appSettings>
<add key="ConnectionString" value="Data Source=.;uid=sa;pwd=111111;Database=SilverlightDB"/>
</appSettings>
接着定义一个和Product表对应的实体类Product.cs
[Serializable]
public class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
再接着是添加一个Web服务,文件名为ProductService.asmx
[WebMethod]
public List<Product> GetAllProduct()
{
List<Product> products= new List<Product>();
//这里是从数据库获取数据,方式可以是ADO.NET、LINQ to sql或者是ADO.NET Entity Framework,以下是用最简单的ADO.NET来实现的
string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
using (sqlConnection con = new sqlConnection(connectionString))
{
con.open();
string strsql = "select * from Product";
sqlCommand cmd = new sqlCommand(strsql,con);
sqlDataReader data = cmd.ExecuteReader();
while (data.Read())
{
Product product = new Product();
product.Name = data["Name"].ToString();
product.Price = double.Parse(data["Price"].ToString());
products.Add(product);
}
}
return products;
}
前台显示页面MainPage.xaml中添加一个ListBox用于显示数据
<ListBox x:Name="myBooks" Margin="101,144,158,124">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBlock Text="{Binding Price}"></TextBlock>
<TextBlock Text="---------------------------------------------------------------"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
在MainPage.xaml.cs文件中编写调用WebService的代码进行数据绑定
private void LayoutRoot_Loaded(object sender,System.Windows.RoutedEventArgs e)
{
// Todo: Add event handler implementation here.
ProductServiceReference.ProductServiceSoapClient client = new NetworkSample.ProductServiceReference.ProductServiceSoapClient();
//注册调用成功事件
client.GetAllProductCompleted += new EventHandler<NetworkSample.ProductServiceReference.GetAllProductCompletedEventArgs>(OnGetAllProductCompleted);
client.GetAllProductAsync();
}
private void OnGetAllProductCompleted(object sender,NetworkSample.ProductServiceReference.GetAllProductCompletedEventArgs e)
{
//检测调用是否成功
if (e.Error != null)
{
return;
}
myBooks.ItemsSource = e.Result;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。