maxp
maxp

Reputation: 25141

TextBlock text aligned right, but positioned from the left in XAML

In WPF XAML, if I have a <TextBlock /> manually positioned 100 pixels to the left, inside a <Canvas />, is it possible that the text, for example 'Hello World', starts drawing at the 100 pixel left mark, *but* then moves leftwards, the more text is added?

Upvotes: 0

Views: 862

Answers (1)

ChrisF
ChrisF

Reputation: 137108

The TextBlock has a TextAlignment property that you would have thought would do what you want.

However, for a Canvas this doesn't work. What you need to do is calculate the length of the text and move the left point of the text block accordingly:

double offset = 0.0;
double difference = (element.Width) - element.ActualWidth;
switch (element.TextAlignment)
{
    case TextAlignment.Center:
        offset = 0.5 * difference;
        break;
    case TextAlignment.Right:
        offset = difference;
        break;
}
element.SetValue(Canvas.LeftProperty, component.LeftProperty + offset);

This should move the TextBlock to the right place.

Upvotes: 2

Related Questions