在需要拖動的控件下加入以下代碼就可以實現拖拽,還可以配置相關函數處理拖拽各個階段事件。
引用部分:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
代碼部分:
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior DragBegun="onDragBegun" DragFinished="dragFinished" Dragging="onDragging" />
</i:Interaction.Behaviors>
(2)在後臺代碼中實現,發現有兩種方式,至於其原理是什麼還有待研究:
方式1:
MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
Interaction.GetBehaviors(this.ContentFrame).Add(dragBehavior);
方式2:
MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
dragBehavior.Attach(this.ContentFrame);
以上兩種方法都會覆蓋子控件和本控件的鼠標右鍵下擊和右鍵彈回事件,但是在本控件中還是可以通過以下配置予以實現:
this.ContentFrame.AddHandler(FrameworkElement.MouseLeftButtonDownEvent,
new MouseButtonEventHandler(ellipse_MouseLeftButtonDown), true);//右鍵下擊
this.ContentFrame.AddHandler(FrameworkElement.MouseLeftButtonUpEvent,
new MouseButtonEventHandler(ellipse_MouseLeftButtonUp), true);//右鍵彈回
配置好了之後,鼠標右鍵下擊和右鍵彈回事件會先於拖拽事件執行,所以在下擊時去掉拖拽效果還是來得及的,去掉代碼如下所示:
Interaction.GetBehaviors(this.ContentFrame).Clear();
(3)一天的糾結,終於使用到了第三種方法,使用margin這東西來實現拖拽,對佈局也木有啥特殊的要求,話不多說,貼點代碼記錄下:
首先配置好各個事件:
this.ContentFrame.AddHandler(FrameworkElement.MouseLeftButtonDownEvent,
new MouseButtonEventHandler(ellipse_MouseLeftButtonDown), true);
this.ContentFrame.AddHandler(FrameworkElement.MouseLeftButtonUpEvent,
new MouseButtonEventHandler(ellipse_MouseLeftButtonUp), true);
this.ContentFrame.MouseMove += new MouseEventHandler(ellipse_MouseMove);
//具體實現代碼
/// <summary>
/// 標識是否可以拖動對象
/// </summary>
private bool isDrag = false;
private Point EndPoint;
//鼠標右鍵單擊事件
{
isDrag = true;
StartPoint = e.GetPosition(LayoutRoot);
//ContentFrame.CaptureMouse();在這裏是必須去掉的,不然子控件中的事件還是沒有反應的!
}
//鼠標移動事件
{
ContentFrame.CaptureMouse();
if (isDrag)
{
EndPoint = e.GetPosition(LayoutRoot);
double y = EndPoint.Y - StartPoint.Y;
double x = EndPoint.X - StartPoint.X;
Thickness newMargin = new Thickness()
{
Left = margin.Left + x,
Top = margin.Top + y,
Right = margin.Right - x,
Bottom = margin.Bottom - y
};
}
}
//鼠標右鍵彈回事件
{
isDrag = false;
}
附註:在實現拖拽的過程中想着可以在容器的拖拽事件中再去配置事件,首先呢,沒有理解Silverlight的Drag事件的原理,另外呢,還是來不及了,去掉該效果可以,添加的話得等一個週期了!