WPF如何使StackPanel可滚动

Tom*_*Tom 4 .net c# wpf visual-studio-2010 stackpanel

在stackpanel中,我在运行时从代码中添加一些标签:我想让stackpanel可滚动.在xaml文件中我有:

<ScrollViewer HorizontalAlignment="Left" Height="299" Margin="592,120,0,0" VerticalAlignment="Top" Width="188" VerticalScrollBarVisibility="Auto">

    <StackPanel x:Name="stackPanelVistaProfiloTessera" Height="292" Width="170"/>

</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

在后面的代码我添加一些标签到stackpanel:

for(.....)
{
    stackPanelVistaProfiloTessera.Children.Add(new Label {....});
}
Run Code Online (Sandbox Code Playgroud)

为什么stackpanel不可滚动?我该如何解决这个问题?

谢谢

Hee*_*til 12

从stackpanel删除高度和宽度..这里工作正常.

<ScrollViewer HorizontalAlignment="Left" Background="Green" Height="299" Margin="592,120,0,0" VerticalAlignment="Top" Width="188" VerticalScrollBarVisibility="Auto">
    <StackPanel x:Name="stackPanelVistaProfiloTessera"  Background="RoyalBlue" >
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
        <Label Height="30" Width="100" Margin="5">label1</Label>
    </StackPanel>
</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样.

在此输入图像描述

如果您使用高度和宽度进行设计,则可以将边距设置为stackpanel.