XAML:
<Grid x:Name="MainGrid">
<ScrollViewer x:Name="canvasScroller"
VerticalScrollBarVisibility="Hidden"
HorizontalScrollBarVisibility="Hidden" >
<Canvas x:Name="LayoutRoot"
Width="1024"
Height="768"
MouseMove="CanvasMove" MouseLeftButtonDown="CanvasDown" MouseLeftButtonUp="CanvasUp" MouseLeave="LayoutRoot_MouseLeave">
<Image Source="yi.jpg"
Width="1024"
Height="768"/>
</Canvas>
</ScrollViewer >
</Grid>
XAML.CS
private double horizontalValue = 0;
private double verticalValue = 0;
bool? moving = null;
Point startingPos = new Point();
Point endingPos = new Point();
private double dx = 0;
private double dy = 0;
bool posChanged = false;
private void CanvasDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
moving = false;
LayoutRoot.Cursor = Cursors.Arrow;
startingPos = e.GetPosition(LayoutRoot);
}
private void CanvasMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if ((moving != null) && (moving == false))
{
moving = true;
posChanged = true;
LayoutRoot.Cursor = Cursors.Hand;
}
if (posChanged)
{
endingPos = e.GetPosition(LayoutRoot);
dx = startingPos.X - endingPos.X;
dy = startingPos.Y - endingPos.Y;
double newPosY = canvasScroller.VerticalOffset + dy;
double newPosX = canvasScroller.HorizontalOffset + dx;
canvasScroller.ScrollToHorizontalOffset(newPosX);
canvasScroller.ScrollToVerticalOffset(newPosY);
}
}
private void CanvasUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
posChanged = false;
LayoutRoot.Cursor = Cursors.Arrow;
}
private void LayoutRoot_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
// 在此处添加事件处理程序实现。
posChanged = false;
LayoutRoot.Cursor = Cursors.Arrow;
}