Search code examples
xaml

Can percentage values be used in XAML?


In html one can say width="20%". This is not allowed in XAML of course. Does anyone know why that is or is there a way to get percentage value support in XAML?


Solution

  • Grid ColumnDefinitions and RowDefinitions allow for proportional units (in addition to fixed pixels and Auto).

    Here are 2 examples:

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="20" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    

    The first column will be as large as necessary to fit all content in the column. The next column is 20 device-independant pixels wide. The remaining Width of the grid will be divided equally among the remaining columns. (100% / 4 = 25% in each)

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="4*"/>
      <ColumnDefinition Width="4*"/>
      <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions>
    

    This code would divide 4 columns into 10%, 40%, 40%, and 10% of the total Grid Width.