silverlight: 通过鼠标拖拽操作显示图片内容
需求:通过鼠标的拖拽操作代替点击滚动条,显示图片的内容。
实现:ScrollViewer+Image 控件,捕获鼠标Mouse down/move/up 事件。
效果图:
1.默认显示图片左上部分。
2.通过拖拽显示图片右下部分。
代码:
---XAML---
<UserControl x:Class="ScrollViewTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="30"></RowDefinition> </Grid.RowDefinitions> <Canvas Grid.Row="0" > <ScrollViewer x:Name="scrollView" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Width="500" Height="400"> <Image Source="/ScrollViewTest;component/Image/TestPic.jpg" Stretch="Fill" MouseLeftButtonDown="Image_MouseLeftButtonDown" MouseLeftButtonUp="Image_MouseLeftButtonUp" MouseMove="Image_MouseMove"></Image> </ScrollViewer> </Canvas> </Grid> </UserControl>
---CS---
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace ScrollViewTest { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } bool isMouseCapture = false; double posX, posY, posH1, posV1; double scrollX, scrollY; private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var element = sender as FrameworkElement; if (element == null) return; //Get current positions posX = e.GetPosition(null).X; posY = e.GetPosition(null).Y; //Set mouse capture status isMouseCapture = true; //Set mouse state element.Cursor = Cursors.Hand; element.CaptureMouse(); } private void Image_MouseMove(object sender, MouseEventArgs e) { var element = sender as FrameworkElement; if (element == null) return; if (isMouseCapture) { //Get current positions posH1 = e.GetPosition(null).X; posV1 = e.GetPosition(null).Y; //Recalculate center points scrollY += (posY - posV1); scrollX += posX - posH1; // Force update layout make sure the verticaloffset/horizontaloffset is updated in time this.scrollView.UpdateLayout(); // Scroll to the position this.scrollView.ScrollToVerticalOffset(scrollY); this.scrollView.ScrollToHorizontalOffset(scrollX); } } private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { var element = sender as FrameworkElement; if (element == null) return; if (isMouseCapture) { // Reset mouse capture status isMouseCapture = false; // Reset curosr state element.Cursor = Cursors.Arrow; element.ReleaseMouseCapture(); } } } }
PS:源码下载 -> https://files.cnblogs.com/files/atuotuo/ScrollViewTest.zip