WPF: How to make empty TextBlock not to occupy space?

泪湿孤枕 提交于 2019-12-21 08:49:30

问题


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.


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/528525/wpf-how-to-make-empty-textblock-not-to-occupy-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!