Change StackPanel location on a Canvas programmatically

时光总嘲笑我的痴心妄想 提交于 2019-12-10 10:43:07

问题


I have stackpanel in a canvas

The stackpanel has

 <Canvas x:Name="MyCanvas">
            <Slider Template="{StaticResource simpleSlider}"  x:Name="seekBar" Thumb.DragStarted="seekBar_DragStarted" Thumb.DragCompleted="seekBar_DragCompleted" Canvas.Left="347" Canvas.Top="746" Width="900" Height="2" />
            <Rectangle Height="5" />

       <StackPanel Canvas.Left="200" Canvas.Right = "100">
       </StackPanel>
 </Canvas>

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

Ie seekBar.Canvas.Left = 50


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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());



来源:https://stackoverflow.com/questions/6818851/change-stackpanel-location-on-a-canvas-programmatically

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