Silverlight实现文件拖拽

最近写Silverlight 4的程序,发现silverlight4支持文件拖拽了,于是就自己着手感受了一下。废话少说,先贴代码:

Xaml文件很简单,直接放了一个ListBox。

<Grid x:Name="LayoutRoot" Background="White">
    <ListBox x:Name="DropTargetListBox" AllowDrop="True" Drop="OnDropTargetListBoxDrop" Margin="0"/>
</Grid>

AllowDrop一定要设为True。

cs:

private void OnDropTargetListBoxDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        FileInfo[] files = (FileInfo[])e.Data.GetData(DataFormats.FileDrop);
        foreach (var item in files)
        {
            (sender as ListBox).Items.Add(item.Name);
        }
    }
}

GetData()方法返回的并不是string类型的数组,而是FileInfo,这样就可以访问到文件的内容了。对于上传头像,上传文件非常方便,免得用户去打开对话框来找到那个文件了。

在Winform和WPF程序中GetData()方法返回的是string的数组,也就是文件的路径。也是因为sl的安全问题,还有一点注意的是sl程序中DragOver事件中不能够去访问数据的,只能在Drop事件中去获取文件。当然为了更好的体验,也可以在DragOver中写一些特效。。。。

就这么多了,今天周六,上会网睡觉…………

posted @ 2010-12-11 22:10  Honker Snow  阅读(1256)  评论(1编辑  收藏  举报