I want to know, is it possible to place an elements in center of the canvas through C# Code in WPF...? If yes please give an example.....
Elements position in WPF
Hi Friends,
I want to know, is it possible to place an elements in center of the canvas through C# Code in WPF...? If yes please give an example.....
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Priya LingePosted Aug 1, 2011, 1:46 AM
Please try this.
canvas cn=new Canvas();
cn.VerticalAlignMent=VerticalAlignment.Center;
cn.HorizontalAlignment = HorizontalAlignment.Center;
cn.Background = new SolidColorBrush(Colors.Red);
cn.Height = 100;
cn.Width = 200;
Button btn = new Button();
btn.Height = 23;
btn.Width = 80;
btn.Content = "Button";
btn.SetValue(Canvas.HorizontalAlignmentProperty,HorizontalAlignment.Center);
btn.SetValue(Canvas.VerticalAlignmentProperty, VerticalAlignment.Center);
btn.SetValue(Canvas.LeftProperty, 59.0);
btn.SetValue(Canvas.TopProperty, 37.0);
cn.Children.Add(btn);
LayoutRoot.Children.Add(cn);
Hope this will help you.
Thanks.
Jaganathan BantheswaranPosted Aug 1, 2011, 1:24 AM
Yes... you can,...
Do something like this.
double left = (Canvas.ActualWidth - element.ActualWidth) / 2;
Canvas.SetLeft(element, left);
double top = (Canvas.ActualHeight - element.ActualHeight) / 2;
Canvas.SetTop(element, top);