2013-10-21 83 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