Positioning a WPF Object inside Canvas

WPF provides various type of techniques to arrange the object. You can use Margin, Canvas and etc. If you like to position your object/control using Absolute Positioning style, then you should like the method below.

WPF provides various types of layout control. You can view the list in Blend

To use absolute positioning techniques, I’m going to use the Canvas to control the position of control and name it cnvMain

Next, drag in a control (I’m using button). You can now enter the X and Y position you want for the control through XAML. The syntax is Canvas.Left and Canvas.Top.

If you want to position the object using VB or C#, you are going to use the SetLeft method. In the following example, I’m position the object/button to be middle of the screen when the user click on the button.

Private Sub btnCenter_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCenter.Click
    Canvas.SetLeft(btnCenter, (cnvMain.ActualWidth – btnCenter.ActualWidth) / 2)
    Canvas.SetTop(btnCenter, (cnvMain.ActualHeight – btnCenter.ActualHeight) / 2)
End Sub

The following screenshots are the result.

After click the button


So in order to do it in XAML, we are going to use Canvas.Left. To achieve the same effect using VB, is using SetLeft.


Filed under Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s