Frecklefoot Frecklefoot - 1 year ago 78
C# Question

Position custom control in Canvas

I have a WPF app that uses a Canvas for it's main UI. Custom controls are added dynamically to the Canvas at runtime. How do I absolutely position these custom controls in the Canvas at runtime? With XAML, it's rather straight-forward:

<Label Name="myCoolLabel"
Content="My Name"
Canvas.Left="{Binding MyLabelX, Mode=OneWay}"
Canvas.Top="{Binding MyLabelY, Mode=OneWay}" />

The Canvas property allows me to set the position via Binding. I could even set it if I didn't use Binding. But the Canvas property isn't available via code.

I've considered adding these controls via XAML and make them invisible by default, and then set their positions at runtime via Binding and make them visible, but this is impractical for several reasons, one being that there could a few dynamic control or dozens.

Is there some way to set the absolute position of a control that's added at runtime? Is it even possible?

Answer Source

Set the Canvas.Top and Canvas.Left attached properties of the child control by their static setter methods.

Canvas.SetLeft(myCoolLabel, 100);
Canvas.SetTop(myCoolLabel, 200);

Then add the control to the Canvas by


where canvas is the name of Canvas control.