2

Say I have a stackpanel with two text blocks, one on top of the other. THey are centred horizontally. But I want to hide one of the text blocks and I want the remaining item to centre vertically according to the remaining space (as if it as the only item). Is this possible?

            <StackPanel Grid.Row="0" >
                <TextBlock Text="Testing!" HorizontalAlignment="Center" FontSize="35">
                </TextBlock>
                <TextBlock  Text="test" HorizontalAlignment="Center" FontSize="25">
                </TextBlock>
            </StackPanel>
erotavlas
  • 4,274
  • 4
  • 45
  • 104
  • You can use a Border inside your stackpanel to achieve this. Say ` ... ` – Prasanth Mar 05 '14 at 04:36
  • I think you're going to need to give us some of your XAML here to help you out. Normally, if you "hide" something (by setting `Visibility` = `Visibility.Collapsed` the layout will act as if it is not there. So something else must be going on. – Tim Mar 05 '14 at 04:40
  • Ok added the xaml. Well I tried the visibility collapsed option but in the preview window the first textbox doesn't move. Does it only take effect when I actually view it on the emulator or device? -- EDIT after trying it in the emulator it didn't make a difference. Visibility collapsed had no effect – erotavlas Mar 05 '14 at 04:42
  • Does it really Veritcally align when both textblocks are visible? As far as I understand the StackPanel will stack things from the top, so both the textblocks should be vertically stacked from the top and the "VerticalAlignment" should not have any effect. – Arif Eqbal Mar 05 '14 at 04:57
  • It seems you're right, vertical alignment doesn't affect the stackpanel items – erotavlas Mar 05 '14 at 05:20

1 Answers1

1

As far as I can see, you can't achieve that with StackPanel only, related question : How can I vertically align a TextBox inside a StackPanel?.

Try to wrap your StackPanel within a fixed-height container (container with height independent from height of if it's content). Then set StackPanel's VerticalAlignment property to Center to make it (along with it's content) centered within parent container. For example :

<Grid Height="100">
    <StackPanel VerticalAlignment="Center">
        <TextBlock Text="Testing!" FontSize="35"/>
        <TextBlock Text="test"/>
    </StackPanel>
</Grid>
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137