2013-10-21 68 views
0

我在ScrollViewer中有一个图像。当我设置图像宽度更大时,Horizo​​ntalScrollBar出现。然后,我设置图像宽度小于ScrollViewer中采用,但这种滚动条仍然会出现,就像这样:WPF ScrollViewer Horizo​​ntalScrollBar不能正常工作

                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; 
     } 
    } 

回答

3

的问题是,当你缩放图像下来你不设置Image控制的Width属性。图像控件实际上会自动保持宽高比(默认情况下,Stretch属性设置为Uniform)。但在图片大小调整时,控件本身会保持您在放大过程中设置的大小。另外请注意我已经纠正了修饰键检查,而不是使用Windows窗体WPF:

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上阅读更多关于它的信息。

+0

谢谢!它工作正常:) – Sakura

+0

此外,你应该看看使用'ScaleTransform'来代替。简单得多。 –

+0

我不知道如何使用它,我是WPF的新手,你能否给我一个相对于我上面的任务的示例链接? – Sakura