locked
How to stretch the width of a TextBlock to the same one of its content in a automatically?

    Question

  • Hello, Dear all,

     

    Take the following as an example:

    <Grid Width="400">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" x:Name="TestButton" Text="The content would be changed at runtime."/>
        <Image Grid.Column="1" Source="xxx..."/>
    </Grid>

    The content of the text block would be changed dynamically at run-time, and there is an image just behind it. What I want is to stretch the text block automatically with the length of the content of the block, and always let the image be behind it without much blank.

     

    How could I achieve this? Thank you all!



    • Edited by B0L Tuesday, February 18, 2014 5:46 AM
    Tuesday, February 18, 2014 5:25 AM

Answers

  • After carefully studying the StackPanel, I found it could solve the issue in the following way:

    <Grid Width="400">
       <StackPanel Orientation="Horizontal">
          <TextBlock Grid.Column="0" x:Name="TestButton" Text="The content would be changed at runtime."/>
          <Image Grid.Column="1" Source="xxx..."/>
       </StackPanel>
    </Grid>

    Namely, using StackPanel to replace the grid columns. This does what I want! Thanks.


    • Edited by B0L Tuesday, February 18, 2014 7:23 AM
    • Marked as answer by B0L Tuesday, February 18, 2014 7:23 AM
    Tuesday, February 18, 2014 7:22 AM