Samuel
Samuel

Reputation: 75

How to bind Font Size to variable Grid Size

I have a grid with 2 columns and 2 rows. A single character (Unicode U+2699) was placed inside the bottom right grid field. It looks like this:

Grid currently

I´d like the character to automatically adjust its font size to fit the grid field it has been placed in (in this case it should be bound to the height of the second grid row, but since in some cases it could be unclear if the height or the width of the grid is smaller, it would be also nice to know how to bind to the lowest of those 2 values).

My implementation so far is something like the following (I simplified it a bit for this example):

<Grid>
   <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition x:Name="heightToBind" Height="40"/>
   </Grid.RowDefinitions>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="14*" />
      <ColumnDefinition Width="*" />
   </Grid.ColumnDefinitions>

   <Button FontSize="{Binding ElementName=heightToBind, Path=Height.Value, Mode=OneWay}" Content="&#x2699;" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" />
</Grid>

The problem here is, that it only works if the height is a fixed value inside the RowDefinitions. I want it to work with the following definition:

<Grid.RowDefinitions>
   <RowDefinition Height="4*"/>
   <RowDefinition x:Name="heightToBind" Height="*"/>
</Grid.RowDefinitions>

As a bonus question I´d also be interested why it might be that the character is placed too low so it is getting cut off at the bottom (I tried VerticalAlignment="Center" for the button but with no effect).

Upvotes: 4

Views: 3032

Answers (2)

Blachshma
Blachshma

Reputation: 17395

You can try using a ViewBox as the button's content:

<Button Grid.Row="1" Grid.Column="1">
    <Button.Content>
        <Viewbox  StretchDirection="Both" HorizontalAlignment="Stretch">
            <TextBlock Text="&#x2699;" />
        </Viewbox>
    </Button.Content>
</Button>

A ViewBox can stretch and scale his child to fill all the available space...

Upvotes: 5

ChrisF
ChrisF

Reputation: 137148

You could try binding to the ActualHeight instead of the Height:

<Button FontSize="{Binding ElementName=heightToBind, Path=ActualHeight.Value, Mode=OneWay}"
        Content="&#x2699;" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Right" />

This should work.

The * on the grid definition means take the available space as the height so it's only determined when the page layout has been prepared for layout. If the height is either unset or changed then the real height is returned in the ActualHeight property.

Upvotes: 1

Related Questions