http://blogs.vertigo.com/personal/swarren/Blog/archive/2007/05/30/drag-to-scroll-in-wpf.aspx
改寫VBCODE如下
Xaml
---------------------------
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="300" Width="300" Loaded="Window_Loaded" PreviewMouseDown="Window_PreviewMouseDown" PreviewMouseMove="Window_PreviewMouseMove" PreviewMouseUp="Window_PreviewMouseUp">
VerticalScrollBarVisibility="Hidden"
>
Code
---------------------------
Partial Public Class Window2
Private mouseDragStartPoint As Point
Private scrollStartOffset As Point
Private Sub Window_PreviewMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
mouseDragStartPoint = e.GetPosition(Me)
scrollStartOffset.X = myScrollViewer.HorizontalOffset
scrollStartOffset.Y = myScrollViewer.VerticalOffset
' Update the cursor if scrolling is possible
'this.Cursor = (myScrollViewer.ExtentWidth > myScrollViewer.ViewportWidth) ||
' (myScrollViewer.ExtentHeight > myScrollViewer.ViewportHeight) ?
' Cursors.ScrollAll : Cursors.Arrow;
Me.CaptureMouse()
MyBase.OnPreviewMouseDown(e)
End Sub
Private Sub Window_PreviewMouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs)
If (Me.IsMouseCaptured) Then
' Get the new mouse position.
Dim mouseDragCurrentPoint As Point = e.GetPosition(Me)
'Determine the new amount to scroll.
Dim delta As New Point
If mouseDragCurrentPoint.X > Me.mouseDragStartPoint.X Then
delta.X = -(mouseDragCurrentPoint.X - Me.mouseDragStartPoint.X)
Else
delta.X = Me.mouseDragStartPoint.X - mouseDragCurrentPoint.X
End If
If mouseDragCurrentPoint.Y > Me.mouseDragStartPoint.Y Then
delta.Y = -(mouseDragCurrentPoint.Y - Me.mouseDragStartPoint.Y)
Else
delta.Y = Me.mouseDragStartPoint.Y - mouseDragCurrentPoint.Y
End If
'Scroll to the new position.
myScrollViewer.ScrollToHorizontalOffset(Me.scrollStartOffset.X + delta.X)
myScrollViewer.ScrollToVerticalOffset(Me.scrollStartOffset.X + delta.Y)
End If
MyBase.OnPreviewMouseMove(e)
End Sub
Private Sub Window_PreviewMouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
If (Me.IsMouseCaptured) Then
Me.Cursor = Cursors.Arrow
Me.ReleaseMouseCapture()
End If
MyBase.OnPreviewMouseUp(e)
End Sub
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
''center the label initially
myLabel.SetValue(Canvas.LeftProperty, ((myScrollViewer.ExtentWidth / 2) - (myLabel.ActualWidth / 2)))
myLabel.SetValue(Canvas.TopProperty, ((myScrollViewer.ExtentHeight / 2) - (myLabel.ActualHeight / 2)))
myScrollViewer.ScrollToHorizontalOffset((myScrollViewer.ExtentWidth / 2) - (myScrollViewer.ViewportWidth / 2))
myScrollViewer.ScrollToVerticalOffset((myScrollViewer.ExtentHeight / 2) - (myScrollViewer.ViewportHeight / 2))
End Sub
End Class
沒有留言:
張貼留言