|
概述
Silverlight 2 Beta 1版本發布了,無論從Runtime還是Tools都給我們帶來了很多的驚喜,如支持框架語言Visual Basic, Visual C#, IronRuby, IronPython,對JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步學Silverlight 2系列》文章帶您快速進入Silverlight 2開發。
本文為系列文章第五篇,利用前面講過的鼠標事件處理實現簡單的拖放功能。
準備XAML
在實現拖放功能中,分為三個步驟:
1.按下鼠標,觸發MouseLeftButtonDown事件,選擇要拖動的對象。
3.放開鼠標,觸發MouseLeftButtonUp事件,停止捕捉事件。
做一個簡單的界面,用一個按鈕來顯示拖放,如下XAML聲明:
<Canvas Background="#46461F"> <Button MouseLeftButtonDown="OnMouseDown" MouseMove="OnMouseMove" MouseLeftButtonUp="OnMouseUp" Canvas.Left="50" Canvas.Top="50" Background="Red" FontSize="18" Width="160" Height="80"> <Button.Content> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <Image Source="smile_6.png"></Image> <TextBlock Text="拖動我" VerticalAlignment="Center" Margin="10"></TextBlock> </StackPanel> </Button.Content> </Button></Canvas>
這里為了界面顯示效果,使用了控件模板,后續會專門講到。
開始拖放操作
開始拖放操作,實現MouseLeftButtonDown事件處理程序,用兩個全局變量來記錄當前鼠標的位置和鼠標是否保持移動。
bool trackingMouseMove = false;Point mousePosition;void OnMouseDown(object sender, MouseButtonEventArgs e){ FrameworkElement element = sender as FrameworkElement; mousePosition = e.GetPosition(null); trackingMouseMove = true; if (null != element) { element.CaptureMouse(); element.Cursor = Cursors.Hand; }}
移動對象
移動對象,實現MouseMove事件處理程序,計算元素的位置并更新,同時更新鼠標的位置。
void OnMouseMove(object sender, MouseEventArgs e){ FrameworkElement element = sender as FrameworkElement; if (trackingMouseMove) { double deltaV = e.GetPosition(null).Y - mousePosition.Y; double deltaH = e.GetPosition(null).X - mousePosition.X; double newTop = deltaV + (double)element.GetValue(Canvas.TopProperty); double newLeft = deltaH + (double)element.GetValue(Canvas.LeftProperty); element.SetValue(Canvas.TopProperty, newTop); element.SetValue(Canvas.LeftProperty, newLeft); mousePosition = e.GetPosition(null); }}
完成拖放操作
完成拖放操作,實現MouseLeftButtonUp事件處理程序。
void OnMouseUp(object sender, MouseButtonEventArgs e){ FrameworkElement element = sender as FrameworkElement; trackingMouseMove = false; element.ReleaseMouseCapture(); mousePosition.X = mousePosition.Y = 0; element.Cursor = null;}
效果顯示
最終,完成后的效果如下
拖動按鈕
結束語
本文實現了一個簡單的拖放功能(示例來自于Silverlight 2 SDK),點擊下載文本示例代碼。
NET技術:一步一步學Silverlight :實現簡單的拖放功能,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。