Search code examples
c#.netwpfvb.netwpf-controls

Making a WPF TextBlock be only grow and not shrink?


In my app I set the Text of the TextBlock named tbkStatus many times.

How can I make the TextBlock be just grow auto to fit the text but not shrink when the text changed?

The StatusText changes every few seconds, There are statuses with long text and short text. I want my TextBlock to fit itself to the size of the longest text that was, and even when there is a short text the TextBlock should not shrink

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="200" Width="400" 
        WindowStartupLocation="CenterScreen" 
        ResizeMode="CanMinimize" Topmost="True">
    <Window.Resources>

    </Window.Resources>
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="AUTO" />
            <RowDefinition Height="AUTO" />
            <RowDefinition Height="AUTO" />
            <RowDefinition Height="AUTO" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock Text="Please wait ..." Grid.Row="1" Margin="6"/>

        <TextBlock Name="tbkStatus" Grid.Row="2" Margin="6" TextWrapping="Wrap" Text="{Binding StatusText}"/>

        <ProgressBar Grid.Row="3" Margin="6" Height="20"/>
        <Button Grid.Row="4" HorizontalAlignment="Center" Padding="24,3" Margin="6" Content="Stop"/>
    </Grid>
</Window>

Solution

  • Xaml only solution:

    <TextBlock Text="{Binding StatusText}"
               MinWidth="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}"
               HorizontalAlignment="Left"/>
    

    This way whenever the Width growths, MinWidth growths too. Hence, the control can't shrink back.