在浏览不同的论坛时,注意到很多人在尝试实现拖放功能时遇到了问题。主要问题出现在尝试从ListBox拖放到类似于画布的Panel时。在这篇文章中,将通过步骤演示如何实现这样的功能。
这里将使用Telerik控件来进行演示。可以从Telerik Silverlight控件页面下载试用版的DLL。使用Silverlight 4 Beta 1实现了演示。同样的事情也可以在Silverlight的早期版本中实现。可以从Silverlight网站下载Silverlight SDK。要开发Silverlight 4应用程序,需要从Microsoft网站下载Visual Studio 2010 Beta 2。
接下来,将实现相同的功能。创建一个Silverlight项目。让在LayoutRoot中创建一个ListBox和一个Canvas:
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox x:Name="lstBox" Margin="10" Grid.Column="0" />
<Canvas x:Name="cnvDropBox" Background="Yellow" Margin="10" Grid.Column="1" />
</Grid>
现在在代码后台,需要为ListBox和Canvas注册拖放事件。使用RadDragAndDropManager类来注册。
RadDragAndDropManager.AddDragInfoHandler(lstBox, OnDragInfo);
RadDragAndDropManager.AddDragQueryHandler(lstBox, OnDragQuery);
RadDragAndDropManager.AddDropInfoHandler(cnvDropBox, OnDropInfo);
RadDragAndDropManager.AddDropQueryHandler(cnvDropBox, OnDropQuery);
RadDragAndDropManager.SetAllowDrop(cnvDropBox, true);
事件的实现如下:
private void OnDragQuery(object sender, DragDropQueryEventArgs e)
{
if (e.Options.Status == DragStatus.DragQuery)
{
var draggedListBoxItem = e.Options.Source as Image;
e.Options.DragCue = draggedListBoxItem.Source;
e.Options.Payload = draggedListBoxItem.Source;
}
e.QueryResult = true;
e.Handled = true;
}
private void OnDragInfo(object sender, DragDropEventArgs e)
{
if (e.Options.Status == DragStatus.DragComplete)
{
// 如果想要克隆,就注释掉这个块
lstBox.Items.Remove(e.Options.Source);
}
}
private void OnDropInfo(object sender, DragDropEventArgs e)
{
var droppablePanel = e.Options.Destination;
if (e.Options.Status == DragStatus.DropComplete && droppablePanel is Canvas)
{
FrameworkElement dragableControl = null;
Point desiredPosition = new Point();
Point currentDragPoint = e.Options.CurrentDragPoint;
Point canvasPosition = cnvDropBox.TransformToVisual(null).Transform(new Point());
if (e.Options.Source is Image)
{
// 创建新实例并更新必要的属性
Image tempDragableControl = e.Options.Source as Image;
dragableControl = new Image() { Source = tempDragableControl.Source };
cnvDropBox.Children.Add(dragableControl);
}
desiredPosition.X = currentDragPoint.X - canvasPosition.X;
desiredPosition.Y = currentDragPoint.Y - canvasPosition.Y;
dragableControl.SetValue(Canvas.LeftProperty, desiredPosition.X);
dragableControl.SetValue(Canvas.TopProperty, desiredPosition.Y);
}
}
private void OnDropQuery(object sender, DragDropQueryEventArgs e)
{
var droppablePanel = e.Options.Destination;
if (e.Options.Status == DragStatus.DropDestinationQuery && droppablePanel is Canvas)
{
e.QueryResult = true;
e.Handled = true;
}
}