开发者

WPF layout issue with nested StackPanel straying outside parent StackPanel

I have a horizontal StackPanel with an image and another StackPanel. The inner StackPanel is vertical with two TextBlocks both of which have TextWrapping set to Wrap. However when the text gets wide the inner StackPanel increases in width so that the TextBlocks don't wrap. The outer StackPanel is staying with the grid layout space it has been given. How can I make the inner StackPanel stay within the bounds of the outer StackPanel?

Here's the relevant section of 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>


You're probably better off with a DockPanel instead of 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>

Lately I'm finding that 2 out of 3 times that I start with StackPanel I end up changing it to DockPanel.

But… are you sure that the outer StackPanel is not expanding beyond the bounds of its grid cell? You might want to make that one a DockPanel as well, with both the Image and the inner DockPanel having DockPanel.Dock="Left".


You could bind your inner StackPanel's width to the Parent StackPanel's width. Something like:

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


Give your inner stackpanel or textblock's a fixed width.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜