NRKirby NRKirby - 1 year ago 38
C# Question

How do I reference a rectangle created programmatically, with XAML?

I am working with WPF for the first time. I am creating a rectangle object & adding it as a child of a canvas.

How do I reference it in XAML?

I want to be able to rotate it over time but don't know how to access it from the MainWindow.xaml code...

I haven't been able to find an answer to this anywhere (maybe you can't do it this way?)


I tried setting the

property of the rectangle to
(in C# code) and then doing

<Rectangle x:Name="Test">
<RotateTransform Angle="-45"/>

(This didn't work)

Answer Source

If you create a control in C#, you cannot access it in XAML. I think you must create the necessary animation in C# too.
Applying your rotation in C# could look like this:

var rect = new Rectangle();
rect.LayoutTransform = new RotateTransform() { Angle = -45 };

The better way would be to generate the Rectangle in XAML and apply there the animation. But this depends on your exact situation. e.g. you can create a single Rectangle in XAML and use this one or you can bind an ItemsControl and create a Rectangle in the ItemTemplate for each entry in the binded list.