嵌套StackPanel偏离父StackPanel之外的WPF布局问题

时间:2010-08-06 18:11:01

标签: wpf stackpanel

我有一个带有图像的水平StackPanel和另一个StackPanel。内部StackPanel是垂直的,有两个TextBlock,它们都将TextWrapping设置为Wrap。但是,当文本变宽时,内部StackPanel的宽度会增加,因此TextBlocks不会换行。外部StackPanel与它已经给出的网格布局空间保持一致。如何使内部StackPanel保持在外部StackPanel的范围内?

以下是XAML的相关部分:

    <StackPanel Name="_imageAndNameStackPanel"
               Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" 
               Orientation="Horizontal"  Margin="12,12,12,0">
        <Image Name="_applicationImage" Source="{Binding Path=ImageUri}" 
               Stretch="Fill" Height="64" Width="64" HorizontalAlignment="Left"
               VerticalAlignment="Top" Margin="0,0,12,0" />
        <StackPanel Name="_nameStackPanel">
            <TextBlock Name="_nameTextBlock" Text="{Binding Path=AppName}" 
                 FontSize="24" VerticalAlignment="Top" TextWrapping="Wrap"/>
            <TextBlock Name="_subtitleTextBlock" Text="{Binding Path=Subtitle"
                 FontSize="18" VerticalAlignment="Top" Margin="0,6,0,0" 
                 TextWrapping="Wrap"/>
        </StackPanel>
    </StackPanel>

3 个答案:

答案 0 :(得分:4)

使用DockPanel代替StackPanel可能会更好。

<StackPanel Name="_imageAndNameStackPanel"
           Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" 
           Orientation="Horizontal"  Margin="12,12,12,0">
    <Image Name="_applicationImage" Source="{Binding Path=ImageUri}" 
           Stretch="Fill" Height="64" Width="64" HorizontalAlignment="Left"
           VerticalAlignment="Top" Margin="0,0,12,0" />
    <DockPanel Name="_nameStackPanel">
        <TextBlock Name="_nameTextBlock" Text="{Binding Path=AppName}" 
             FontSize="24" VerticalAlignment="Top" TextWrapping="Wrap" 
             DockPanel.Dock="Top" />
        <TextBlock Name="_subtitleTextBlock" Text="{Binding Path=Subtitle"
             FontSize="18" VerticalAlignment="Top" Margin="0,6,0,0" 
             TextWrapping="Wrap" DockPanel.Dock="Top"/>
    </DockPanel>
</StackPanel>

最近,我发现从StackPanel开始的3次中有2次我最终将其更改为DockPanel

但是......你确定外部StackPanel没有超出其网格单元格的界限吗?您可能希望将该值设为DockPanelImage和内DockPanel都有DockPanel.Dock="Left"

答案 1 :(得分:0)

您可以将内部StackPanel的宽度绑定到Parent StackPanel的宽度。类似的东西:

{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Path=Width}

答案 2 :(得分:-1)

为内部堆叠面板或文本块提供固定宽度。