Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility Collapsed leaving a slight space in the UI

Tags:

wpf

xaml

Given the following xaml structure

<Grid>
    <StackPanel>
      <TextBlock>
           <TextBlock>Block 1</TextBlock>
           <TextBlock>Block 2</TextBlock>
         </TextBlock>
      <TextBlock>
           <TextBlock Visibility="Collapsed">Block 3</TextBlock>
           <TextBlock>Block 4</TextBlock>
      </TextBlock>
      <TextBlock>
           <TextBlock>Block 5</TextBlock>
           <TextBlock>Block 6</TextBlock>
         </TextBlock>
    </StackPanel>
  </Grid>

I expect this output:

Block 1 Block 2 
Block 4 
Block 5 Block 6

But I get this

Block 1 Block 2 
 Block 4   
Block 5 Block 6

Where is the space before Block 4 coming from, and how do I make it go away?

like image 859
Forty-Two Avatar asked Aug 27 '13 13:08

Forty-Two


People also ask

What does visibility collapse mean?

hidden means the element is invisible, though the space it takes on the page remains. collapsed means the element is invisible, AND the space it takes on the page is gone, but it only applies to table elements (otherwise, just like hidden ).

What is the difference between visibility hidden and collapse?

visible: It is used to specify the element to be visible. It is a default value. hidden: Element is not visible, but it affects layout. collapse: It hides the element when it is used on a table row or a cell.


1 Answers

By using Snoop, you can see that this is from a ContainerVisual that wraps your child TextBlocks. Since TextBlock is trying to display a collection of Inline derived objects (this is generally abstracted away), it must wrap your TextBlock in a ContainerVisual.

Since these are the actual objects getting arranged by the parent TextBlock, and they don't even have the Visibility property, you are going to need to refactor your code a bit. I imagine that you're trying to bind to a number of separate properties, and want to display them in one TextBlock. You could fix this a couple of ways:

  • Make a IMultiValueConverter and pass a bunch of properties controlling what to show
  • Construct the complex string in your ViewModel
  • Replace the outer TextBlock with a StackPanel with Orientation="Horizontal"

I'd recommend the last, as it is the easiest.

<StackPanel>
   <StackPanel Orientation="Horizontal">
        <TextBlock>Block 1</TextBlock>
        <TextBlock>Block 2</TextBlock>
   </StackPanel>
   <StackPanel Orientation="Horizontal">
        <TextBlock Visibility="Collapsed">Block 3</TextBlock>
        <TextBlock>Block 4</TextBlock>
   </StackPanel>
   <StackPanel Orientation="Horizontal">
        <TextBlock>Block 5</TextBlock>
        <TextBlock>Block 6</TextBlock>
   </StackPanel>
</StackPanel>
like image 123
Abe Heidebrecht Avatar answered Nov 11 '22 05:11

Abe Heidebrecht