Tuesday, February 23, 2010

WPF ViewBox: Starting at other than the default size

I wanted my Chessboard to shrink when I resized the window:

 

ChessBoard - Without ViewBox ChessBoard - With ViewBox

Without ViewBox

With ViewBox

 

Without ViewBox

 

<TextBlock Grid.Row="0"

           Grid.Column="0"

           HorizontalAlignment="Right"

           VerticalAlignment="Center"

           FontSize="12" 

           FontFamily="Consolas" Text="{Binding Path=AlgebraicIdentity, Mode=OneWay}"/>

<TextBlock Grid.Row="0"

           Grid.RowSpan="2"

           HorizontalAlignment="Center"

           VerticalAlignment="Center"

           FontFamily="Chess Cases" FontSize="48"

           Text="{Binding Path=CurrentPiece.AltChar, Mode=OneWay}"  />

With ViewBox

 

<Viewbox Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Stretch">

    <TextBlock

        FontSize="12" 

        FontFamily="Consolas" Text="{Binding Path=AlgebraicIdentity, Mode=OneWay}"/>

</Viewbox>

<Viewbox Grid.RowSpan="2" Grid.Row="0">

    <TextBlock HorizontalAlignment="Center"

               VerticalAlignment="Center"

               FontFamily="Chess Cases" FontSize="48" Text="{Binding Path=CurrentPiece.AltChar, Mode=OneWay}"  />

</Viewbox>

Aside:  Please ignore the bindings.  Actually, I’m using an Open source chess font called ‘Chess Cases’.  All you need to do is use ‘k’ for King.  The AltChar you see above is this.

Question:  If you use ViewBox, it’ll pick a starting size in accordance with its own calculation.  So, you’ll see:

 

With ViewBox Without ViewBox
King - WithViewBox King - NoViewBox

Now, How do I make the ‘With ViewBox’ version start respecting the start size (which is 48 as you see in the without ViewBox version)?

Answer is easier than I thought it would be:

    <TextBlock FontFamily="Chess Cases"

               Margin="3,3,3,3" Text="{Binding Path=CurrentPiece.AltChar, Mode=OneWay}"  />

Use Margin!

No comments: