Translation of Canvas child not working when setting its LayoutTransform to a TranslateTransform or MatrixTransform

StackOverflow https://stackoverflow.com/questions/12054349

  •  27-06-2021
  •  | 
  •  

I have a simple application consisting of a Window containing a Canvas (rootCanvas). I am trying to add another Canvas (test) to this and apply different Transforms to the child canvas's LayoutTransform. This is all being done programmatically rather than using XAML.

Some transforms are working, whilst others are not as follows:

  • When the LayoutTranform is set to a RotateTransform it works as expected.
  • When it is set to a TranslateTransform the translation does not appear to be applied, and the test Canvas is still located in the top corner of rootCanvas
  • When it is set to a MatrixTransform that has been constructed by applying a rotation and then a translation, only the rotation appears to be applied.

The code is given below:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Canvas rootCanvas = (Canvas)Application.Current.Windows[0].FindName("canvas1");

        Canvas test = new Canvas();
        test.Width = 10;
        test.Height = 10;
        test.Background = Brushes.Aqua;

        // this works 
        //test.LayoutTransform = new RotateTransform(45);

        // this doesn't
        //test.LayoutTransform = new TranslateTransform(40, 40);

        // only the rotate part of this works
        Matrix matrix = new Matrix();
        matrix.Rotate(45);
        matrix.Translate(40, 40);
        test.LayoutTransform = new MatrixTransform(matrix);

        rootCanvas.Children.Add(test);
    }
}

I would be extremely grateful if someone could explain what I am doing wrong here, as I do not understand why translations do not seem to be working as I would expect.

Thanks in advance,

Wibbs

有帮助吗?

解决方案

Please read the remarks in FrameworkElement.LayoutTransform Property.

However, LayoutTransform ignores TranslateTransform operations.

Use UIElement.RenderTransform Property for applying a TranslateTransform.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top