ScrollView内部的StackPanel无法正确滚动

时间:2011-08-24 16:49:23

标签: c# wpf xaml scrollview stackpanel

考虑以下XAML(UserControl):

<Grid x:Name="LayoutRoot" ScrollViewer.VerticalScrollBarVisibility="Disabled">
    <Grid HorizontalAlignment="Right" Width="335.312" ScrollViewer.VerticalScrollBarVisibility="Disabled">
        <ed:BlockArrow Fill="#FFF4F4F5" HorizontalAlignment="Left" Margin="0" Orientation="Left" Stroke="Black" Width="15" RenderTransformOrigin="5.6,-0.412" Height="12" VerticalAlignment="Center" MouseEnter="LeftArrow_MouseEnter" MouseLeave="LeftArrow_MouseLeave" MouseLeftButtonUp="LeftArrow_MouseLeftButtonUp"/>
        <ed:BlockArrow Fill="#FFF4F4F5" Stroke="Black" RenderTransformOrigin="5.6,-0.412" Height="12" VerticalAlignment="Center" MouseEnter="RightArrow_MouseEnter" MouseLeave="RightArrow_MouseLeave" HorizontalAlignment="Right" Width="15" MouseLeftButtonUp="RightArrow_MouseLeftButtonUp"/>
        <ScrollViewer x:Name="panelScrollViewer" Margin="15,0" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Hidden">
            <StackPanel x:Name="slidingStackPanel" Orientation="Horizontal" Height="125.882" Width="305.312" ScrollViewer.VerticalScrollBarVisibility="Disabled" CanHorizontallyScroll="True" ScrollViewer.CanContentScroll="False"/>
        </ScrollViewer>
    </Grid>
</Grid>

我希望实际滚动此堆栈面板。我动态地将元素添加到stackpanel,这似乎正常工作。在另一个按钮的单击功能中,执行以下代码:

panelScrollViewer.ScrollToHorizontalOffset(100);

scrollview和stackpanel的Horizo​​nalOffset仍为零!此外,stackpanel的ScrollOwner为null。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

由于您没有指定ScrollViewer的宽度,因此它需要StackPanel的大小。由于ScrollViewer的内容不大于其大小,因此它不会滚动,并且始终具有0的水平偏移。尝试将ScrollViewer的宽度设置为小于其内容的值,并且您应该有一个工作的水平滚动。 / p>

同样删除所有禁用垂直滚动条的冗余,一旦足够好。

<Grid x:Name="LayoutRoot">
<Grid HorizontalAlignment="Right" Width="335.312">
    <ed:BlockArrow Fill="#FFF4F4F5" HorizontalAlignment="Left" Margin="0" 
         Orientation="Left" Stroke="Black" Width="15" RenderTransformOrigin="5.6,-0.412"
         Height="12" VerticalAlignment="Center" MouseEnter="LeftArrow_MouseEnter" 
         MouseLeave="LeftArrow_MouseLeave" MouseLeftButtonUp="LeftArrow_MouseLeftButtonUp"/>
    <ed:BlockArrow Fill="#FFF4F4F5" Stroke="Black" RenderTransformOrigin="5.6,-0.412" 
         Height="12" VerticalAlignment="Center" MouseEnter="RightArrow_MouseEnter" 
         MouseLeave="RightArrow_MouseLeave" HorizontalAlignment="Right" Width="15" 
         MouseLeftButtonUp="RightArrow_MouseLeftButtonUp"/>
    <ScrollViewer x:Name="panelScrollViewer" Margin="15,0" CanContentScroll="False" 
          VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Hidden"
          Width="250">
        <StackPanel x:Name="slidingStackPanel" Orientation="Horizontal" Height="125.882" Width="305.312"/>
    </ScrollViewer>
</Grid>