ScrollViewer在Canvas中不起作用

时间:2016-08-27 01:28:56

标签: c# xaml windows-runtime winrt-xaml

我想在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>
      <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>

但如果我用Canvas切换Grid一切正常。有没有办法让ScrollViewerCanvas内工作?

1 个答案:

答案 0 :(得分:2)

根据您帖子中包含的代码,您似乎没有给出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的大小限制为小于其内容大小的内容都会导致滚动条变得可见和可用。