调整子项大小时,保持scrollviewer的相对滚动条偏移量

时间:2014-06-26 19:17:53

标签: c# wpf

我有一个带有网格的滚动查看器作为孩子。我正在更改网格的宽度和高度属性以显示不同的"缩放"水平。网格包含2行,其中包含许多相同大小的图像列。

但是,我希望滚动条的相对位置保持不变。在更改网格尺寸后,屏幕中心的任何内容仍应位于屏幕中央。

默认"放大"视图:

private void SizeGrid()
{
    grid1.Width = (scrollViewer1.ViewportWidth / 2) * grid1.ColumnDefinitions.Count;
    grid1.Height = (scrollViewer1.ViewportHeight / 2) * grid1.RowDefinitions.Count;        
}

"放大"视图:

private void scrollViewer1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.IsKeyDown(Key.Insert))
    {
        grid1.Width = (scrollViewer1.ViewportWidth / 2) * grid1.ColumnDefinitions.Count / 5;
        grid1.Height = (scrollViewer1.ViewportHeight / 2) * grid1.RowDefinitions.Count / 3;
    }
}

我尝试做什么 ......

如果我知道什么专栏专注(我不想知道这一点):

double shiftAmount = (scrollViewer1.ScrollableWidth / (grid1.ColumnDefinitions.Count - columnsOnScreen));
scrollViewer1.ScrollToHorizontalOffset(column * shiftAmount);

如果我不确切知道他们正在查看哪一列,但我只是想保持相对位置......

double previousScrollRatio = scrollViewer1.HorizontalOffset / scrollViewer1.ScrollableWidth;
//resize grid...
scrollViewer1.ScrollToHorizontalOffset(previousScrollRatio * scrollViewer1.ScrollableWidth);

这两种方法都不奏效。如果我以滚动条居中缩小,则滚动条将转到最右侧。有什么想法吗?

可以找到最小代码示例here以及上面的scroll_KeyDown方法。


默认缩放的屏幕截图:

enter image description here

缩小后的屏幕截图,不正确(海军蓝和粉红色方块远离屏幕):

enter image description here

缩小后的屏幕截图, 应该是什么样的:

enter image description here

2 个答案:

答案 0 :(得分:7)

这是一种在放大或缩小时将内容保持在中心的解决方案

    //variables to store the offset values
    double relX;
    double relY;
    void scrollViewer1_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        ScrollViewer scroll = sender as ScrollViewer;
        //see if the content size is changed
        if (e.ExtentWidthChange != 0 || e.ExtentHeightChange != 0)
        {
            //calculate and set accordingly
            scroll.ScrollToHorizontalOffset(CalculateOffset(e.ExtentWidth, e.ViewportWidth, scroll.ScrollableWidth, relX));
            scroll.ScrollToVerticalOffset(CalculateOffset(e.ExtentHeight, e.ViewportHeight, scroll.ScrollableHeight, relY));
        }
        else
        {
            //store the relative values if normal scroll
            relX = (e.HorizontalOffset + 0.5 * e.ViewportWidth) / e.ExtentWidth;
            relY = (e.VerticalOffset + 0.5 * e.ViewportHeight) / e.ExtentHeight;
        }
    }

    private static double CalculateOffset(double extent, double viewPort, double scrollWidth, double relBefore)
    {
        //calculate the new offset
        double offset = relBefore * extent - 0.5 * viewPort;
        //see if it is negative because of initial values
        if (offset < 0)
        {
            //center the content
            //this can be set to 0 if center by default is not needed
            offset = 0.5 * scrollWidth;
        }
        return offset;
    }

背后的想法是存储最后一个滚动位置,并在内容大小改变时使用它来计算新的偏移量,这将改变范围。

只需将ScrollChanged的事件ScrollViewer附加到构造函数等中的此事件处理程序,然后将其余部分保留给它。

例如

    scrollViewer1.ScrollChanged += scrollViewer1_ScrollChanged;

上述解决方案将确保将网格保持在中心位置,即使是第一次加载

居中内容的样本

放大

zoomed in

缩小

zoomed out

<强>附加

我还尝试为同一个创建一个可附加的行为,因此您不需要连接事件,只需设置属性将启用或禁用该行为

namespace CSharpWPF
{
    public class AdvancedZooming : DependencyObject
    {
        public static bool GetKeepInCenter(DependencyObject obj)
        {
            return (bool)obj.GetValue(KeepInCenterProperty);
        }

        public static void SetKeepInCenter(DependencyObject obj, bool value)
        {
            obj.SetValue(KeepInCenterProperty, value);
        }

        // Using a DependencyProperty as the backing store for KeepInCenter.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty KeepInCenterProperty =
            DependencyProperty.RegisterAttached("KeepInCenter", typeof(bool), typeof(AdvancedZooming), new PropertyMetadata(false, OnKeepInCenterChanged));

        // Using a DependencyProperty as the backing store for Behavior.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BehaviorProperty =
            DependencyProperty.RegisterAttached("Behavior", typeof(AdvancedZooming), typeof(AdvancedZooming), new PropertyMetadata(null));

        private static void OnKeepInCenterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ScrollViewer scroll = d as ScrollViewer;

            if ((bool)e.NewValue)
            {
                //attach the behavior
                AdvancedZooming behavior = new AdvancedZooming();
                scroll.ScrollChanged += behavior.scroll_ScrollChanged;
                scroll.SetValue(BehaviorProperty, behavior);
            }
            else
            {
                //dettach the behavior
                AdvancedZooming behavior = scroll.GetValue(BehaviorProperty) as AdvancedZooming;
                if (behavior != null)
                    scroll.ScrollChanged -= behavior.scroll_ScrollChanged;
                scroll.SetValue(BehaviorProperty, null);
            }
        }

        //variables to store the offset values
        double relX;
        double relY;
        void scroll_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            ScrollViewer scroll = sender as ScrollViewer;
            //see if the content size is changed
            if (e.ExtentWidthChange != 0 || e.ExtentHeightChange != 0)
            {
                //calculate and set accordingly
                scroll.ScrollToHorizontalOffset(CalculateOffset(e.ExtentWidth, e.ViewportWidth, scroll.ScrollableWidth, relX));
                scroll.ScrollToVerticalOffset(CalculateOffset(e.ExtentHeight, e.ViewportHeight, scroll.ScrollableHeight, relY));
            }
            else
            {
                //store the relative values if normal scroll
                relX = (e.HorizontalOffset + 0.5 * e.ViewportWidth) / e.ExtentWidth;
                relY = (e.VerticalOffset + 0.5 * e.ViewportHeight) / e.ExtentHeight;
            }
        }

        private static double CalculateOffset(double extent, double viewPort, double scrollWidth, double relBefore)
        {
            //calculate the new offset
            double offset = relBefore * extent - 0.5 * viewPort;
            //see if it is negative because of initial values
            if (offset < 0)
            {
                //center the content
                //this can be set to 0 if center by default is not needed
                offset = 0.5 * scrollWidth;
            }
            return offset;
        }
    }
}

启用行为

通过xaml

<ScrollViewer l:AdvancedZooming.KeepInCenter="True">

<Style TargetType="ScrollViewer" x:Key="zoomCenter">
    <Setter Property="l:AdvancedZooming.KeepInCenter"
            Value="True" />
</Style>

或通过代码

scrollViewer1.SetValue(AdvancedZooming.KeepInCenterProperty, true);

AdvancedZooming.SetKeepInCenter(scrollViewer1, true);

通过样式或以编程方式设置内联属性l:AdvancedZooming.KeepInCenter="True",以便在任何scrollviewer上启用行为

l:在本例中指的是AdvancedZooming类xmlns:l="clr-namespace:CSharpWPF"的命名空间

答案 1 :(得分:0)

这可能听起来有点复杂但是如果你使用屏幕坐标将对象的中心(在网格单元格中)与滚动条的中心对齐?

您可以使用PointToScreen获取屏幕坐标中的对象坐标,并在缩小或放大后对齐它。

private void OnMouseMove(object sender, MouseEventArgs e)
{
    var element = (UIElement)e.Source;

    int c = Grid.GetColumn(element);
    int r = Grid.GetRow(element);
}

只有在每个单元格中都有UIElements时,这才有效。

或者您可以尝试this来获取坐标。

这只是一个假设,因为我无法正确测试它。