文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Silverlight中WebClient下载资源

Silverlight中WebClient下载资源

时间:2011-04-24  来源:chenping2008

首先新建一个Silverlight应用程序带Web的,在Web程序中放入一个txt文件,名为TextFile1.txt。内容Silverlight is very good!

然后在silverlight项目中添加一个silverlight user control名为WebClientDownResource.xaml

xaml的内容为:

<Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition>
            </ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto">
            </RowDefinition>
            <RowDefinition Height="auto">
            </RowDefinition>
            <RowDefinition Height="auto" >
            </RowDefinition>
        </Grid.RowDefinitions>
        
        <Button Grid.Row="1" Grid.Column="0" Content="DownText" Height="23" HorizontalAlignment="Left"  Name="Down" VerticalAlignment="Top" Width="75" Margin="12,0,0,0" Click="Down_Click" />
        <TextBlock  Grid.Row="0" Grid.Column="0" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="350" />
        <ProgressBar Grid.Row="2" Grid.Column="0" Height="10" HorizontalAlignment="Left" Margin="10,10,0,0" Name="progressBar1" VerticalAlignment="Top" Width="100" />

    </Grid> 

后台的代码:

private void Down_Click(object sender, RoutedEventArgs e)

        {
            string uri = Application.Current.Host.Source.AbsoluteUri;
            int index = uri.IndexOf("/ClientBin");
            uri = uri.Substring(0, index) + "/TextFile1.txt";

            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            webClient.OpenReadAsync(new Uri(uri));
        }

        void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }
        private void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // (Add code to display error or degrade gracefully.)
            }
            else
            {
                Stream stream = e.Result;
               StreamReader reader=new StreamReader(stream);
                this.textBlock1.Text=reader.ReadToEnd();
                reader.Close();
            }
        } 
具体的关于webclient的内容可以参考《pro silverlight 4 in c#》中的第6章内容。
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载