Thursday, October 11, 2007 2:27 AM
sporter
Centering and Sizing Text in Silverlight
One of the things that I find myself doing over and over in Silverlight is centering text in TextBlock objects. The majority of the time I am doing this for headers, footers, and other areas where I have a single line of text. Often I find that I also need to size text within a TextBlock appropriately for the containing space. The algorithm is the same whether you do this in Silverlight 1.0 vs. 1.1, but I will show both. In figure 1 you see the XAML that we will be working with, figure 2 shows the JavaScript needed to center the text using Silvelright 1.0, and figure 3 shows the managed C# needed to center the text using Silverlight 1.1.
|
<Canvas x:Name="textCanvas" Width="640" Height="480"> <TextBlock x:Name="CenteredText" Text="This Text Should Be Centered." Width="640" Height="480" /> </Canvas>
|
Fig 1. XAML
|
var headerText = this.target.findName("CenteredText")
while(headerText.ActualWidth > headerText.Width) { headerText.FontSize -= 0.5; }
var newLeft = ((headerText.Width - headerText.ActualWidth) / 2) + this.headerText.GetValue("Canvas.Left");
headerText.SetValue("Canvas.Left", newLeft);
var newTop = ((headerText.Height - headerText.ActualHeight) / 2) + this.headerText.GetValue("Canvas.Left");
headerText.SetValue("Canvas.Top", newTop);
|
Fig 2. Centering and sizing text in JavaScript
|
while(CenteredText.ActualWidth > CenteredText.Width) { CenteredText.FontSize -= 0.5; }
double newLeft = ((CenteredText.Width - CenteredText.ActualWidth) / 2) + (double)CenteredText.GetValue(Canvas.LeftProperty);
CenteredText.SetValue(Canvas.LeftProperty, newLeft);
double newTop = ((CenteredText.Height - CenteredText.ActualHeight) / 2) + (double)CenteredText.GetValue(Canvas.TopProperty);
CenteredText.SetValue(Canvas.TopProperty, newTop);
|
Fig 3. Centering and sizing text in Managed C#
First findName is called to get a reference to the TextBlock object of which you are centering the text. This step is only required in the 1.0 version; you will already have a strongly typed reference in 1.1. Next a while loop is executes that decreases the font size of the TextBlock object until the actual width is less than or equal to the width. Next a new left and top position is calculated and set for the TextBlock object. The text is not actually centered in the TextBlock object since there is no support for centering, instead the TextBlock object itself is moved to the appropriate left and top positions to give the illusion of being centered.
In a scenario where you need to set the text property of a TextBlock repeatedly you will need to cache the initial left and top position of the object so that you have the same starting point every successive time you center the text.