Right-align a TextBlock in Silverlight

There is currently no way to right-align a TextBlock UI Element in Silverlight, though you can use this workaround to properly position your TextBlock to make it appear right-aligned:

The XAML

<Canvas>
    <TextBlock Text="My Text" Loaded="TextBlock_Loaded" Width="80"/>
</Canvas>

The Loaded event handler

       private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock) sender;
            Canvas.SetLeft(tb, Canvas.GetLeft(tb) + tb.Width - tb.ActualWidth);
        }

By wrapping the TextBlock in the Canvas container, you can fix its position easily.

Advertisements

1 Response to “Right-align a TextBlock in Silverlight”


  1. 1 fail March 4, 2012 at 10:01 pm

    Didn’t work… Width is NaN, even after the TextBlock has loaded.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: