可以通過跟蹤StackPanel的Children-property的index-element來實現。我發給你一些示例代碼,演示了這個工作。例如,請考慮以下代碼:
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);
}
它獲取當前選定的TextBlock並將其索引向上移動一個。然後您需要通過刪除並重新插入來更新StackPanel的Children-property。
我問你是否想用這種類型的目的使用StackPanel。使用ItemsControl比ListBox更容易,因爲它們可以綁定到T的ObservableCollection。更新綁定集合後,控件也會同樣更新。
我希望這會有所幫助。示例代碼可以下載here。
「改變位置」是什麼意思?你想重新排列物品還是將其移動到屏幕上? – ChrisF
你想要達到的是什麼? – pdvries
我想改變兩個元素的位置,例如我想要改變Textblock 1,4 –