Mihir
Mihir

Reputation: 89

Height and width of text block as per text

Is it possible to set the height and width of text block as per the text?The text is given to the text block dynamically ?

 TextBlock myTextBlockj = new TextBlock() 
   { Text = "Hello World", 
     Width =150, 
     Height = 40, 
     FontSize = 20 
   };

The text of text block is "Hello World".I want to set width of text block of size same as text.If text changes the width of text block should change.

Anyone have idea about it?

Upvotes: 0

Views: 225

Answers (3)

MVarman
MVarman

Reputation: 549

All you need is, TextWrapping = TextWrapping.Wrap

In Code:

TextBlock myTextBlockj = new TextBlock() 
{
    Text = "Hello World", 
    HorizontalAlignment = HorizontalAlignment.Left, 
    VerticalAlignment = VerticalAlignment.Top, 
    TextWrapping = TextWrapping.Wrap
};

In Xaml:

<TextBlock Text="Hello world" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" />

Also, you might need TextTrimming in case the text exceeds the available space.

Upvotes: 2

Nanosoft
Nanosoft

Reputation: 119

For Height you may try

LineHeight="Auto"

Upvotes: 0

Rhyous
Rhyous

Reputation: 6690

All you have to do is set the VerticalAlignment and the HorizontalAlignments to something other than stretch.

Here is a one page example:

<Window x:Class="TextblockMinSize.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Text="Hello, world!" HorizontalAlignment="Left" VerticalAlignment="Top"/>
    </Grid>
</Window>

And in code you have:

TextBlock myTextBlockj = new TextBlock()
{
    Text = "Hello World",
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top
};

Upvotes: 0

Related Questions