WPF ScrollViewer Horizo​​ntalScrollBar无法正常工作

时间:2013-10-21 04:47:59

标签: wpf scrollviewer horizontalscrollview

我在ScrollViewer中有一个图像。当我将图像宽度设置得更大时,出现了Horizo​​ntalScrollBar。然后我将图像宽度设置为小于ScrollViewer With,但此ScrollBar仍然出现,如下所示:

IMG
我该如何解决这个问题?谢谢!

<Grid>
    <ScrollViewer
        Name="sv"
        HorizontalScrollBarVisibility="Auto"
        VerticalScrollBarVisibility="Auto"
        PreviewMouseWheel="sv_PreviewMouseWheel">
        <Image Name="img"/>
    </ScrollViewer>
</Grid>

代码:

    void sv_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        if ((System.Windows.Forms.Control.ModifierKeys & System.Windows.Forms.Keys.Control) != System.Windows.Forms.Keys.Control) base.OnMouseWheel(e);
        else
        {
            if (e.Delta > 0)
            {
                if (img.ActualHeight < img.Source.Height * 5)
                {
                    double h2 = img.Height = img.ActualHeight * 1.1;
                    double w2 = img.Width = img.Source.Width * h2 / img.Source.Height;
                }
            }

            // PROBLEM HERE:

            else if (img.ActualHeight > 100) img.Height = img.ActualHeight / 1.1;
        }
    }

1 个答案:

答案 0 :(得分:3)

问题是,当您缩小图像时,您没有设置Image控件的Width属性。图像控件实际上自动保持宽高比(默认情况下Stretch属性设置为Uniform)。但是,当图像调整大小时,控件本身会保持您在放大期间设置的大小。另请注意,我已更正您的修改键检查以使用WPF而不是Windows窗体:

void sv_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
    {
        double? h2 = null;
        if (e.Delta > 0)
        {
            if (img.ActualHeight < img.Source.Height * 5)
            {
                h2 = img.Height = img.ActualHeight * 1.1;
            }
        }
        else if (img.ActualHeight > 100)
        {
          h2 = img.Height = img.ActualHeight / 1.1;
        }

        if (h2 != null)
        {
             img.Width = img.Source.Width * h2.Value / img.Source.Height;
        }
    }
}

另一种解决方案是使用变换来缩放图像。

<强> XAML

<Image Name="img"
       HorizontalAlignment="Center"
       VerticalAlignment="Center">
    <Image.LayoutTransform>
        <ScaleTransform x:Name="imageScale" />
    <Image.LayoutTransform>
</Image>

<强> C#

void sv_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
    {
        e.Handled = true; // stops scrolling due to wheel

        if (e.Delta > 0)
        {
            if (imageScale.ScaleX < 5)
            {
                imageScale.ScaleX *= 1.1;
                imageScale.ScaleY *= 1.1;
            }
        }
        else
        {
            imageScale.ScaleX /= 1.1;
            imageScale.ScaleY /= 1.1;
        }
    }
}

您也可以使用其他变换,例如旋转。请在MSDN上了解详情。