一步一步学Silverlight :数据与通信之ASMX
编写展示界面,XAML如下,与上一篇中的示例一样:
<Grid Background="#46461F"> <Grid.RowDefinitions> <RowDefinition Height="40"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <Border Grid.Row="0" Grid.Column="0" CornerRadius="15" Width="240" Height="36" Background="Orange" Margin="20 0 0 0" HorizontalAlignment="Left"> <TextBlock Text="最新随笔" Foreground="White" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20 0 0 0"></TextBlock> </Border> <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> </Grid>
实现调用ASMX,并进行数据的绑定。仍然采用异步模式,所使用的方法如上图中红色框中的部分。过程与WCF通信差不多,只不过不再需要指定Bingding等信息:
public partial class Page : UserControl { public Page() { InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { BlogServiceSoapClient client = new BlogServiceSoapClient(); client.GetPostsCompleted += new EventHandler<GetPostsCompletedEventArgs>(client_GetPostsCompleted); client.GetPostsAsync(); } void client_GetPostsCompleted(object sender, GetPostsCompletedEventArgs e) { if (e.Error == null) { Posts.ItemsSource = e.Result; } } }
一个完整的Silverlight 2中调用ASMX的示例就完成了,运行后效果如下:
结束语
本文简单介绍了在Silverlight 2中如何调用ASMX,你可以从这里下载示例代码。