SilverLight中数据与通信之WCF
1. 新建一个实体类接口文件IBlog.cs
// 注意: 如果更改此处的接口名称 "IBlog",也必须更新 Web.config 中对 "IBlog" 的引用。
[ServiceContract]
public interface IBlog
{
[OperationContract]
Post[] GetPosts();
}
[DataContract]
public class Post
{
public Post(int id, string title, string author)
{
this.Id = id;
this.Title = title;
this.Author = author;
}
[DataMember]
public int Id { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Author { get; set; }
}
2. 新建一个实体类文件Blog.svc
// 注意: 如果更改此处的类名 "Blog",也必须更新 Web.config 中对 "Blog" 的引用。
//注意:web.config中的binding默认的是wsHttpBinding,需修改为basicHttpBinding,
//<endpoint address="" binding="basicHttpBinding" contract="Binglang.SilverlightDemo9.Web.IBlog">
public class Blog : IBlog
{
public Post[] GetPosts()
{
List<Post> posts = new List<Post>()
{
new Post(1,"一步一步学Silverlight 2系列(13):数据与通信之WebRequest","TerryLee"),
new Post(2,"一步一步学Silverlight 2系列(12):数据与通信之WebClient","TerryLee"),
new Post(3,"一步一步学Silverlight 2系列(11):数据绑定","TerryLee"),
new Post(4,"一步一步学Silverlight 2系列(10):使用用户控件","TerryLee"),
new Post(5,"一步一步学Silverlight 2系列(9):使用控件模板","TerryLee"),
new Post(6,"一步一步学Silverlight 2系列(8):使用样式封装控件观感","TerryLee")
};
return posts.ToArray();
}
}
2. 调用
前台代码:
<ListBox x:Name="Posts" Grid.Row="1" Margin="40 10 10 10">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Id}" Height="40" Foreground="Red"></TextBlock>
<TextBlock Text="{Binding Title}" Height="40"></TextBlock>
<TextBlock Text="{Binding Author}" Height="40" Foreground="Orange"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
后台代码:
Loaded+=new RoutedEventHandler(MainPage_Loaded);
//实现调用wcf,并进行数据的绑定。采用异步模式。过程与调用webService通信差不多,只不过需要指定Bingding等信息。
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress("http://localhost:52424/Blog.svc");
BlogClient client = new BlogClient(binding, endPoint);
client.GetPostsCompleted += new EventHandler<GetPostsCompletedEventArgs>(client_GetPostsCompleted);
client.GetPostsAsync();
}
void client_GetPostsCompleted(object sender, GetPostsCompletedEventArgs e)
{
if (e.Error == null)
{
Posts.ItemsSource = e.Result;
}
}