Search code examples
c#wpfxamltextblock

How to set Textblock size to always fit the bound data?


I am working on a WPF GUI. I have many views and everyview has several TextBlocks, I am trying to get rid of an annoying design (I know red is annoying but that's not the case) so I will explain with couple sample Text Blocks and here is its XAML:

Sometimes there is data "Binding behind", sometimes it's a single word sometimes it's couple words and sometime there is not data at all. How can I set them beside each other whatever the data is?

<TextBlock x:Name="sessionNameTextBlock" Margin="0,0,1123,9.8" Text="{Binding CurrentSessionName}" VerticalAlignment="Bottom" FontSize="48" TouchUp="sessionNameTextBlock_TouchUp" MouseUp="sessionNameTextBlock_MouseUp" Height="57" Background="#FFE81616"/>
<Border x:Name="SessionEditorButton" BorderBrush="Black" BorderThickness="0" Margin="48,0,1027,9.8" MouseUp="SessionEditorButton_MouseUp" TouchUp="SessionEditorButton_TouchUp" Background="#FFF91515" Height="57" VerticalAlignment="Bottom">
   <Image x:Name="image" Margin="10,10,9.8,10.6" Source="/EZ3D;component/Resources/ez3d_edit.png"/>
</Border>
<TextBlock x:Name="sessionCommentsTextBlock" Margin="144,0,975,9.8" Text="{Binding CurrentSessionComments}" MouseUp="sessionCommentsTextBlock_MouseUp" TouchUp="sessionCommentsTextBlock_TouchUp" FontSize="18.667" Background="#FFF41515" Height="57" VerticalAlignment="Bottom"/>

The current state is this: enter image description here

Or if I manually resize it: enter image description here

What I would like to have is this:

------------- Vision----------------

In execution one the contents are 'S' and 'E', then execution two the contents are "Whatever... etc" and "Comments ... etc" So the TextBlock will resize depends on its content. enter image description here


Solution

  • So the following XAML behaves as you requested for me.

    <StackPanel Orientation="Horizontal">
        <TextBlock x:Name="tb1" Text="Test" />
        <Border x:Name="SessionEditorButton" BorderBrush="Black" BorderThickness="0" Background="#FFF91515" Height="57" VerticalAlignment="Bottom">
            <Image x:Name="image" Margin="10,10,9.8,10.6" />
        </Border>
        <TextBlock x:Name="tb2" Text="Test 2"/>
    </StackPanel>
    

    Granted this works in a very contrived example, but what it comes down to is that the TextBlocks will automatically resize themselves if their container has the space to allow it. In this case my StackPanel fills the window so there is plenty of room for the TB's to resize. You may need to look at your container hierarchy to figure out which container is contraining your text blocks.