Welsh King
Welsh King

Reputation: 3238

Change StackPanel location on a Canvas programmatically

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

Upvotes: 2

Views: 3598

Answers (4)

kedarK
kedarK

Reputation: 213

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

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

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.

Upvotes: 0

Mario Vernari
Mario Vernari

Reputation: 7304

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.

Upvotes: 2

Yiğit Yener
Yiğit Yener

Reputation: 5986

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

Upvotes: 1

Related Questions