WPF text scaling October 26, 2008Posted by wesaday in Programming.
Had a wonderful time with this. I needed a way to scale the text in a WPF app that would change the size of the text according to how big the window was sized. You would think that that would be a normal thing to do. Wrong! After much seraching, frustration, searching and more frustration I had one of those “Duh” moments. This also illistrates the change in thinking that is required when dealing with WPF.
The first thing that you find is that a Viewbox control scales everything that is contained within it. Sounds easy don’t it? Well if you want the text inside a button control to scale, the first thing that you think of is to put the button in the Viewbox. However, that produces a really ugly effect. At least to me it was an undesired effect. as you can see the button border is exagerated. As the window is sized, the effect gets more and more noticeable.
Enter the Duh moment.
In WPF you can nest containers within containers within containers. You cannot think of a Button as just a Button control. You have to think of the Button as a container. I am too lazy to look up the XMAL for a button at the moment but the stock button control probably has a border, another border and probably a textblock to contain the text. So if you think about it, the button width and height will take care of themselves. All you really want is the text to scale. So what you really want to do is to put the viewbox inside the button! Duh!
This is what the button now looks like. The button looks like a normal button and the text scales up and down as the container window is resized. Here is the XAML:
<Button Grid.Column="2" Grid.Row="4"> <Button.Content> <Viewbox> <TextBlock>Test</TextBlock> </Viewbox> </Button.Content> </Button>