ScrollViewer不能在Canvas中工作

本文关键字:工作 Canvas 不能 ScrollViewer | 更新日期: 2023-09-27 18:04:09

我试图在Canvas内使用ScrollViewer,但滚动不起作用。

<Page
    x:Class="ScrollViewerInCanvas.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScrollViewerInCanvas"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
  <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Canvas>
      <ScrollViewer>
        <StackPanel Orientation="Vertical" Width="400">
          <TextBlock Text="Just a huge text that will not fit into a single frame"
                     FontSize="100" TextWrapping="WrapWholeWords" />
        </StackPanel>
      </ScrollViewer>
    </Canvas>
  </Grid>
</Page>

但是如果我把CanvasGrid交换,一切都有效。有没有办法让ScrollViewer工作在Canvas里面?

ScrollViewer不能在Canvas中工作

根据你在帖子中包含的代码,似乎你没有给ScrollViewer任何需要滚动的理由。Canvas元素不会以任何方式约束它的子元素。所以在Canvas中,ScrollViewer可以想怎么大就怎么大,这样它就足够大,可以在不滚动的情况下容纳它的子元素。在Grid中,它会被拉伸以适合它的单元格,所以如果单元格比子单元格小,它将允许滚动。给它一个滚动的理由,它就会滚动。

例如,您可以使ScrollViewer始终与其父Canvas具有相同的尺寸:

<Page
    x:Class="ScrollViewerInCanvas.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScrollViewerInCanvas"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
  <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Canvas x:Name="canvas1">
      <ScrollViewer Width="{Binding ActualWidth, ElementName=canvas1}"
                    Height="{Binding ActualHeight, ElementName=canvas1}">
        <StackPanel Orientation="Vertical" Width="400">
          <TextBlock Text="Just a huge text that will not fit into a single frame"
                     FontSize="100" TextWrapping="WrapWholeWords" />
        </StackPanel>
      </ScrollViewer>
    </Canvas>
  </Grid>
</Page>

任何将ScrollViewer的大小限制为小于其内容大小的方法都会使滚动条变得可见和可用。