Search code examples
c#xamlwindows-phone-8

How to set items on left and right with grid column in windows phone 8.0


Can anyone say how to do like that:

In a pop-up I have two items one textblock and one image, in function of size of text I need to put all times text on left and icon right, like in the second picture.

 <Grid>
    <Grid.ColumnDefinitions>
       <ColumnDefinition Width="Auto"/>
       <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
         <TextBlock Grid.Column="0" Text="TEXT"/>
         <Image Grid.Column="1" />
 </Grid>

First Image is like that when first column is set auto: enter image description here

When set an static width:

 <Grid>
        <Grid.ColumnDefinitions>
           <ColumnDefinition Width="400"/>
           <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
             <TextBlock Grid.Column="0" Text="TEXT"/>
             <Image Grid.Column="1" />
     </Grid>

After set

enter image description here

I want to set dynamic, not with a static value in width.


Solution

  • You can set the HorizontalAlignment of the element in the grid:

    <Grid HorizontalAligment="Stretch">
        <Grid.ColumnDefinitions>
           <ColumnDefinition Width="Auto"/>
           <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
             <TextBlock Grid.Column="0" Text="TEXT"/>
             <Image Grid.Column="1" HorizontalAlignment="Right" />
    </Grid>
    

    This should put the image on the right hand side of the column. You might find you have to tell the grid to stretch to fill it's container as well.

    Alternatively, assuming that your icons are the same sizes, you could swap the column definitions:

    <Grid HorizontalAligment="Stretch">
        <Grid.ColumnDefinitions>
           <ColumnDefinition Width="*"/>
           <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
             <TextBlock Grid.Column="0" Text="TEXT"/>
             <Image Grid.Column="1" />
    </Grid>
    

    so that the second column takes it width from its content (the icons) and the first stretches to fill the available space.

    With this sort of problem you often have to try two or three things to get the exact behaviour you're looking for.