Frecklefoot
Frecklefoot

Reputation: 1692

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"
       Width="200"
       Height="100"
       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?

Upvotes: 0

Views: 529

Answers (1)

Kassim Shaikh
Kassim Shaikh

Reputation: 63

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

canvas.Children.Add(myCoolLabel);

where canvas is the name of Canvas control.

Upvotes: 1

Related Questions