WPF: How to make empty TextBlock not to occupy space?
Asked Answered
U

2

11

Let's say that I have a simple layout such as this:

<StackPanel>
  <TextBlock Text="{Binding Path=Title}" />
  <TextBlock Text="{Binding Path=ShortDescription}" />
  <TextBlock Text="{Binding Path=LongDescription}" />
</StackPanel>

Now when I have ShortDescription set to null or empty string there's still a gap in place of second TextBlock. Is there some property to prevent an empty textblock from occupying space? Or should I use some other control?

Thanks.

Unguarded answered 9/2, 2009 at 15:9 Comment(0)
A
20

You want to set the visibility of the textbox to "Collapsed".

Visibility can be either:
Visible - Self explanatory
Hidden - Invisible but still takes up space
Collapsed - Invisible and takes up no space

Edit: You should probably set up a trigger, like so:

<Trigger Property="Text" Value="{x:Null}">
    <Setter Property="Visibility" Value="Collapsed"/>
</Trigger>
Aldwin answered 9/2, 2009 at 15:13 Comment(1)
This will only work if the value is null, if you want to set the visibility on a null or empty string, you will want to use a converter. This thread discusses how to do that.Martell
B
9

You may want to try this:

<TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
        <Style.Triggers>
            <Trigger Property="Text" Value="">
                <Setter Property="Visibility" Value="Collapsed"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

This should fix the empty space issue based on a Null / Empty Binding.

Bullace answered 29/7, 2011 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.