在上次項目中寫過多篇關于拖拽的實作. 這些拖拽都是控件之間的效果. Silverlight 4 中我們甚至可以直接把檔案系統中檔案拖拽到Silverlight Application中承載. 這就是 silverlight 4中新特性Silverlight As Drop Target 支援這一點. 為了達到示範目的. 使用桌面圖檔拖拽到Silverlight Application中ScrollViewer動态顯示. 先體驗一下[你可以嘗試從本地檔案系統直接拖拽圖檔到這個Silverlight Application中看一下效果]:
<a href="http://blog.51cto.com/attachment/201201/171702236.jpg" target="_blank"></a>
實作步驟:
<1>: 頁面布局
<StackPanel x:Name="LayoutRoot" Background="White">
<TextBlock Text=" "></TextBlock>
<TextBlock Text="Silverlight AS Drop target.-chenkai[10.6.28]" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="16" Foreground="Red" FontFamily="Comic Sans MS" FontWeight="BOld" Height="25" Width="655" />
<ScrollViewer x:Name="ImagesTarget" Background="White" Height="360" BorderBrush="Red"
VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" AllowDrop="True">
<ItemsControl x:Name="ImageList" Height="353">
<!--定義資料模闆 支援格式是Image圖檔 很重要 不然會包invaid異常 資料模闆确實很強大.-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Margin="5" Stretch="UniformToFill" Height="240" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<!--項排序模式Horizontal 居中-->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</StackPanel>
<2>:背景實作代碼
//定義存儲Image集合.
ObservableCollection<BitmapImage> _images = new ObservableCollection<BitmapImage>();
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
//如果Image資料則直接加載進來.
ImageList.ItemsSource = _images;
ImagesTarget.Drop += new DragEventHandler(ImagesTarget_Drop);
void ImagesTarget_Drop(object sender, DragEventArgs e)
//判斷拖拽資料是否存在
if (e.Data == null)
{
return;
}
else
//利用Fileinfo 來初始化關于檔案系統日常操作io對象 Fileinfo 【】數組 意味支援多張Image同時拖拽Silverlight Application
IDataObject dataObject = e.Data as IDataObject;
FileInfo[] files =dataObject.GetData(DataFormats.FileDrop) as FileInfo[];
foreach (FileInfo file in files)
{
try
{
using (var stream = file.OpenRead())
{
//讀取拖拽中圖檔源.
var imageSource = new BitmapImage();
imageSource.SetSource(stream);
//添加到集合中.
_images.Add(imageSource);
}
}
catch (Exception)
MessageBox.Show("Not a suppoted image.");
}
本文轉自chenkaiunion 51CTO部落格,原文連結:http://blog.51cto.com/chenkai/764886