Silverlight实用窍门系列:42.读取拖动到控件上的外部txt和jpg文件,多外部文件的拖动【附带实例源码】

        本实例将读取拖动到Silverlight的ListBox控件中的txt文件或者Jpg文件。在本实例中将讲如果通过UIelementA.Drop事件获取到拖动到UIelementA上的文件的相关名称以及路径等信息,以处理多个外部文件拖动到Silverlight中的相关一些小技巧的应用和操作。

        在本例中我们设置外部文件拖动到ListBox中去,首先我们要设置ListBox的AllowDrop="True",再添加一个Drop事件Drop="listBox1_Drop",这样在外部文件拖动到ListBox中的时候可以触发Drop事件。

        首先我们来看MainPage.xaml代码如下所示:

    <Grid x:Name="LayoutRoot" Background="White" Width="600">
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="600" 
                    Orientation="Horizontal">
            <ListBox Name="listBox1" Background="AliceBlue" Width="240"
                     HorizontalAlignment="Left" VerticalAlignment="Top" 
                     AllowDrop="True" Height="400" Drop="listBox1_Drop">
            </ListBox>
            <TextBlock Height="149" HorizontalAlignment="Left" 
                       Name="textBlock1" VerticalAlignment="Top" 
                       Width="323" TextWrapping="Wrap" />
        </StackPanel>
            <Image Height="238" Name="image1" HorizontalAlignment="Left"
                   VerticalAlignment="Top" Margin="240 160 0 0" Stretch="Fill"
         Width="320" Source="/SLDragFile;component/Images/1_24573_f93ae69954e2e1d.jpg" />
    </Grid>

       在上面有一个TextBlock显示读取到的Txt文件内容,还有一个Image控件显示读取到的图片内容。下面我们看MainPage.xaml.cs文件代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
using System.Windows.Markup;
using System.Windows.Media.Imaging;

namespace SLDragFile
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void listBox1_Drop(object sender, DragEventArgs e)
{
//获取与拖放事件相关联的元素
IDataObject dataObject = e.Data as IDataObject;
//返回被拖放的外部文件的 FileInfo 数组
FileInfo[] files = dataObject.GetData(DataFormats.FileDrop) as FileInfo[];

foreach (FileInfo file in files)
{
//如果存在文件
if (file.Exists)
{
listBox1.Items.Add(
"文件名: " + file.Name);
//如果是txt文件,读取txt文件并且显示出来
if (file.Extension.ToLower() == ".txt")
{
StreamReader sreader
= file.OpenText();
string txtstr = "";
string ReadStr = string.Empty;
while ((txtstr = sreader.ReadLine()) != null)
{
ReadStr
+= txtstr;
}
this.textBlock1.Text = ReadStr;
}
//如果是Jpg图片,读取图片并且显示出来
if (file.Extension.ToLower() == ".jpg")
{
FileStream fs
= file.OpenRead();
BitmapImage image
= new BitmapImage();
image.SetSource(fs);
image1.Source
= image;

}
}
else
{
listBox1.Items.Add(
"文件添加失败!");
}
}
}
}
}

        下面我们来看看拖动一张jpg图片文件的效果如下:

        拖动一个UTF-8格式的txt文件的效果如下:

        拖动多个文件到ListBox所出现的情况如下面三张图片所示:

        本文采用VS2010+Silverlight 4.0编写,如需源码请点击 SLDragFile.zip 下载

posted @ 2011-05-23 10:18  .NET架构  阅读(2548)  评论(16编辑  收藏  举报