Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the position of an element in Stackpanel?

Tags:

wpf

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?

like image 868
ar.gorgin Avatar asked Dec 03 '25 17:12

ar.gorgin


1 Answers

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.

like image 120
pdvries Avatar answered Dec 06 '25 08:12

pdvries