我对该如何处理这个问题有一些基本的误解。
我在ScrollViewer里有一块画布。我想能够在画布上放大和缩小,并有适当的ScrollViewer调整。
代码如下:
XAML编号:
<Window x:Class="scrollerProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<ScrollViewer Name="scroller" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Canvas Background="AntiqueWhite" Name="content" MouseLeftButtonDown="content_MouseLeftButtonDown" MouseRightButtonDown="content_MouseRightButtonDown">
<Rectangle Width="100" Height="100" Canvas.Top="50" Canvas.Left="50" Fill="PaleGoldenrod"></Rectangle>
</Canvas>
</ScrollViewer>
</Window>
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace scrollerProblem
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
float Zoom = 1;
public Window1()
{
InitializeComponent();
content.Width = 700;
content.Height = 700;
}
private void content_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
content.Width *= 2; // BLAH
content.Height *= 2; // BLAH
Zoom *= 2;
TransformGroup gridTransforms = new TransformGroup();
gridTransforms.Children.Add(new ScaleTransform(Zoom, Zoom));
gridTransforms.Children.Add(new TranslateTransform(0, 0));
content.RenderTransform = gridTransforms;
}
private void content_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
content.Width /= 2; // BLAH
content.Height /= 2; // BLAH
Zoom /= 2;
TransformGroup gridTransforms = new TransformGroup();
gridTransforms.Children.Add(new ScaleTransform(Zoom, Zoom));
gridTransforms.Children.Add(new TranslateTransform(0, 0));
content.RenderTransform = gridTransforms;
}
}
}
如果我省略了标有“BLAH”的行,滚动条根本不会调整…这并不奇怪,因为实际上没有任何东西改变内容画布的大小。但是,如果我在画布中添加了空洞的线条,画布会收缩/增长,但同时它也在缩放,这意味着与内容相比,它看起来并不正确。
我猜我采取了一种根本错误的方法,但我不清楚如何解决它。这是正确的方法,只是一个小问题,还是我在这里采取了完全错误的策略?