Reputation: 365
How can I (programatically) set the font size of a TextBlock
in a WPF Canvas
?
The text size should be relative to the canvas dimensions, so that it is centered.
This works for my local machine, but displayed on a larger screen, the text is cut off halfway up.
double fontSize = TickerOverlay.Height / 2.5;
Is there a simple way to do this, so that If the canvas dimensions increase (say, displayed on a larger resolution screen), the text will still be centered?
Upvotes: 4
Views: 9498
Reputation: 1
you can subscribe to loaded event in the xaml, like this:
<TextBlock Loaded="TextBlock_Loaded"/>
And, in codebehind you update it, like this:
private void TextBlock_Loaded(object sender, RoutedEventArgs e)
{
var myTextBlock = sender as TextBlock;
if(myTextBlock != null)
{
myTextBlock.FontSize = TickerOverlay.Height / 2.5;
}
}
Upvotes: 0
Reputation: 585
First, you should use the ActualHeight of you TickerOverlay instead of the Height. It will give the real height in real time.
Secondly, you could listen to the SizeChanged of you TickerOverlay, and update the font size of your text in the event handler.
Upvotes: 0
Reputation: 439
The correct way to do this in a model view controller layout is for this to be handled by the view (In this case XAML). WPF has a component, the ViewBox, that works well for this case.
<Grid>
<Viewbox HorizontalAlignment="Center" Grid.Row="1" VerticalAlignment="Center" Height="50">
<TextBlock Margin="10 0 10 0">Hello World</TextBlock>
</Viewbox>
</Grid>
The viewbox automatically expands to fill up all available space and sets the font to fit. Height is how you set the max font size, though it will shrink if it reaches 100%. Use the margin to ensure it doesn't go off the page.
Upvotes: 5
Reputation: 1486
You don't need to set the font size. Wrap your canvas in a ViewBox, and it should work fine.
ViewBox is a control that scales whatever's inside it to fit it's available space. So if you've set the canvas as it should, it would scale it up or down depending on the resolution.
Upvotes: 1