WPF如何阻止scrollviewer在缩放过程中上下移动

4jb9z9bj  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(145)

我在ScrollViewer中有一个Grid。我为网格设置了一个长高度。
动态地,我添加一个Canvas到我的网格,并在其中添加2个矩形。鼠标缩放事件正在工作,但当我启动应用程序并向下滚动到2个框的末尾,我试图用鼠标缩放时,scrollviewer会上升到其起始位置。我不想禁用它,我希望它继续显示,但不向上移动。

  • MainWindow.xaml
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" Name="sv">
    <Grid Name="myGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="5000" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="330" />
        </Grid.ColumnDefinitions>
    </Grid>
</ScrollViewer>
  • MainWindow.xaml.cs
public partial class MainWindow : Window
{
    double currentZoom = 0;
    ScaleTransform scaleTransform;
    TransformGroup transformGroup;

    public MainWindow()
    {
        InitializeComponent();
        scaleTransform = new ScaleTransform();
        transformGroup = new TransformGroup();

        transformGroup.Children.Add(scaleTransform);
        begin();
    }
    private void begin()
    {
        Canvas canvas = new Canvas();
        Rectangle rectangle1 = new Rectangle
        {
            Width = 300,
            Height = 600,
            Fill = new SolidColorBrush(Color.FromRgb(255, 255, 255)),
            StrokeThickness = 2,
            Stroke = Brushes.Black
        };
        Canvas.SetLeft(rectangle1, 100);
        Canvas.SetTop(rectangle1, 100);
        canvas.Children.Add(rectangle1);

        Rectangle rectangle2 = new Rectangle
        {
            Width = 300,
            Height = 600,
            Fill = new SolidColorBrush(Color.FromRgb(255, 255, 255)),
            StrokeThickness = 2,
            Stroke = Brushes.Black
        };
        Canvas.SetLeft(rectangle2, 200);
        Canvas.SetTop(rectangle2, 200);
        canvas.Children.Add(rectangle2);

        myGrid.Children.Add(canvas);
        myGrid.RenderTransform = transformGroup;
        myGrid.MouseWheel += (sender, e) => wheelEvent(sender, e);
    }
    private void wheelEvent(object sender, MouseWheelEventArgs e)
    {
        Point position = e.GetPosition(myGrid);

        scaleTransform.CenterX = position.X;
        scaleTransform.CenterY = position.Y;

        var newZoom = e.Delta / 120 / (double)50;
        scaleTransform.ScaleX = 1 + newZoom + currentZoom;
        scaleTransform.ScaleY = 1 + newZoom + currentZoom;
        currentZoom += newZoom;
    }
}
uqcuzwp8

uqcuzwp81#

可以使用MouseWheelEventArgs.Handled属性来停止其他事件处理程序执行它们的操作。

private void wheelEvent(object sender, MouseWheelEventArgs e)
{
    //Might be a good idea to use some custom condition
    //that determines if you are zooming or not like:
    //if(!IsCtrlButtonPressed) return;
    //If you return with e.Handled == false 
    //ScrollViewer's handler will scroll you normally

    //suppress MouseWheel event and other MouseWheel responders
    e.Handled = true;

    //your zooming logic
}

更多信息:MSDN

相关问题