天天看点

Silverlight调用自定义的Web Service从数据库获取数据进行页面绑定

    Silverlight调用WebService只能使用异步方式调用。所谓异步方式调用就是让调用方法的主线程不必同步等待在这个函数调用上,从而允许主线程继续执行它下面的代码。

    Silverlight调用自定义的WebService分为四个步骤:

   (1)、创建自定义的WebService

   (2)、实现WebService

   (3)、在Silverlight项目中添加服务引用

   (4)、使用异步方式调用WebService

下面举例介绍:

    比如说在MSSQL2000中建立一个名为SilverlightDB的数据库,里面包含一张表Product,里面有2个字段Name和Price,举例说明字段就随便用两个意思意思下。

    在Web.Config文件中配置数据库连接字符串

   <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

  在其中添加一个获取产品列表的方法GetAllProduct

         [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;

至此,一个Silverlight调用自定义的WebService的案例就做好了。