我正在尝试创建带有滚动条的画布。谁能帮我就如何做到这一点提供一些想法?我已经尝试过使用 1 行 1 列的网格,但由于某些限制,我想使用画布。
提前致谢!
我正在尝试创建带有滚动条的画布。谁能帮我就如何做到这一点提供一些想法?我已经尝试过使用 1 行 1 列的网格,但由于某些限制,我想使用画布。
提前致谢!
您可以将画布放在滚动查看器中。我尝试了这个快速测试,它允许我滚动画布的内容。
<ScrollViewer Height="100" Width="200">
<Canvas Height="400" Width="400">
//Content here
</Canvas>
</ScrollViewer>
编辑:这是一个示例,其中滚动条仅在需要时显示,并且随着画布大小的变化而动态变化。
<Button Content="Change Canvas Size" Click="ChangeCanvasSize_Click"/>
<ScrollViewer Height="100" Width="200" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<Canvas x:Name="TestCanvas">
<TextBlock Text="Test Test"/>
</Canvas>
</ScrollViewer>
通过单击按钮更改画布大小:
private void ChangeCanvasSize_Click(object sender, RoutedEventArgs e)
{
TestCanvas.Width = 600;
TestCanvas.Height = 600;
}
在此示例中,我一开始没有滚动条,当我单击按钮展开画布时,会出现滚动条。
Ok after working with it for sometime I figured out a way. Create a XAML like this
<ScrollViewer>
<Grid x:Name="drawingGrid" SizeChanged="drawingGrid_SizeChanged">
<Canvas Name="drawingCanvas"> /<Canvas>
</Grid>
</ScrollViewer>
On windowLoad function set the canvas height/width equal to grid height/width. Update the canvas ht/wd:
dragging an element beyond the boundaries of canvas or creating a new element too close the edge of canvas
double dHeight = 220;
if (drawingCanvas.Height < CurrentPosition.Y + dHeight)
{
// increase canvas height
drawingCanvas.Height += (2 * dHeight);
}
Hope this is of some help. Please share if anyone has any better idea or suggestions to improve this.
通过结合 Mario-sannum 的回答和您的问题,我制定了一个在大多数情况下都可以正常工作的解决方案。
<ScrollViewer>
<Grid x:Name="drawingGrid" SizeChanged="drawingGrid_SizeChanged">
<Canvas Name="c">
<TextBlock x:Name="draw_Text" Text="Test Test"/>
</<Canvas>
</Grid>
</ScrollViewer>
void drawingGrid_SizeChanged(object sender, SizeChangedEventArgs e)
{
try { c.Height = draw_Text.ActualHeight; } catch { }
try { c.Width = draw_Text.ActualWidth; } catch { }
}
那应该调整画布的大小,以便滚动查看器可以滚动......