Change StackPanel location on a Canvas programmatically

扶醉桌前 提交于 2019-12-06 13:41:23

The "Canvas.Left" is an example of attached dependency property. The syntax for the C# is:

Canvas.SetLeft(myStackPanel, 50);

Where myStackPanel is any custom name you must assign using x.Name in the xaml.

You should use Canvas.SetLeft and Canvas.SetRight methods.

Caveat: I'm assuming that by this:

At runtime i need to change the location of the objects within the StackPanel.

You mean that you need to be able to set the Left position of the StackPanel itself (irrespective of what it contains). If this is not what you mean (for example, you don't have anything called seekBar in your example Xaml, even though you reference it in your code), please clarify.


The Canvas uses Attached Dependency Properties (as do other layout items, such as the Grid) to track layout information about contained items. Because of this, you'll either have to use the GetLeft and SetLeft functions on Canvas, GetValue and SetValue functions on your StackPanel to manipulate these values.

Do this, you'll need to give your StackPanel a name. I'll call it stack.

Given your example, you would do either this:

Canvas.SetLeft(stack, 50);

or this:

stack.SetValue(Canvas.LeftProperty, 50);

Note that the first version (SetLeft) is simply a wrapper around the second version, so use whichever you prefer.

You can get the value of any control by var x = btn.TransformToAncestor(this).Transform(new Point(0, 0)); where btn is the control which you want the margin of.

And then use yourstackpanel.SetValue(StackPanel.MarginProperty,new Thickness());

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!