Search code examples
c#xamlrendertransform

How to use CompositeTransform in C#?


How can I code this XAML code in C#?

<TextBlock Text="..." RenderTransformOrigin="0.5,0.5">
                    <TextBlock.RenderTransform>
                        <CompositeTransform TranslateY="-25"/>
                    </TextBlock.RenderTransform>
                </TextBlock>

I tried in this way:

private TextBlock dots;
dots = new TextBlock();
dots.Text = "...";
dots.RenderTransformOrigin = new Point(0.5, 0.5); 
(dots.RenderTransform as CompositeTransform).TranslateY = 20;

But I get a System.NullReferenceException. I also tried in this way:

var ct = (CompositeTransform)dots.RenderTransform;
            ct.TranslateY = 20;

But I get a System.InvalidCastException (Unable to cast object of type 'System.Windows.Media.MatrixTransform' to type 'System.Windows.Media.CompositeTransform'.)

Thanks in advance!


Solution

  • If you're creating a new control from scratch, it's RenderTransform property will be an Identity MatrixTransform, so you can't cast it to CompositeTransform. You'd have to do it like this:

    dots.RenderTransform = new CompositeTransform { TranslateY = 20 };