I have a Stackpanel with 5 child .
<StackPanel Orientation="Horizontal">
<TextBlock >1</TextBlock>
<TextBlock >2</TextBlock>
<TextBlock >3</TextBlock>
<TextBlock >4</TextBlock>
<TextBlock >5</TextBlock>
</StackPanel>
I want change the position of child[2].
How do change the position of an element in runtime?
It can be achieved by keeping track of the index-element of the Children-property of the StackPanel. I send you some sample code that demonstrates the working of this. For instance, consider the following code:
int currentSelectedIndex = stackPanel1.Children.IndexOf(CurrentSelectedTextBlock);
int downIndex = currentSelectedIndex + 1;
int childCount = stackPanel1.Children.Count;
if (downIndex < childCount)
{
stackPanel1.Children.RemoveAt(currentSelectedIndex);
stackPanel1.Children.Insert(downIndex, CurrentSelectedTextBlock);
}
else if (downIndex == childCount)
{
stackPanel1.Children.RemoveAt(currentSelectedIndex);
stackPanel1.Children.Insert(currentSelectedIndex, CurrentSelectedTextBlock);
}
It gets the currently-selected TextBlock and moves its index up one higher. You then need to update the Children-property of the StackPanel by removing and inserting it back again.
I question whether you want to use a StackPanel for this type of purpose. It's much easier to use an ItemsControl, like a ListBox as they can be bound to a ObservableCollection of T. Once the bound collection is updated, the control is updated likewise.
I hope this helps. The sample code can be download here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With