2012-10-21 27 views
2

我有一個有5個孩子的Stackpanel。如何更改Stackpanel中元素的位置?

<StackPanel Orientation="Horizontal"> 
     <TextBlock >1</TextBlock> 
     <TextBlock >2</TextBlock> 
     <TextBlock >3</TextBlock> 
     <TextBlock >4</TextBlock> 
     <TextBlock >5</TextBlock> 
    </StackPanel> 

我想改變孩子的位置[2]。

在運行時如何改變元素的位置?

+0

「改變位置」是什麼意思?你想重新排列物品還是將其移動到屏幕上? – ChrisF

+0

你想要達到的是什麼? – pdvries

+0

我想改變兩個元素的位置,例如我想要改變Textblock 1,4 –

回答

0

這個問題有點不明確,因爲意圖沒有列出非常具體。下面的代碼可以移動基於文本的內容屬性的TextBlock:

 string number = "4"; 
    TextBlock textBlockToSearch = null; 

    foreach (var child in stackPanel1.Children) 
    { 
     if (child is TextBlock) 
     { 
      var textBlock = (TextBlock) child; 
      if (textBlock.Text.CompareTo(number) == 0) 
       textBlockToSearch = textBlock; 
     } 
    } 

    if (textBlockToSearch != null) 
    { 
     stackPanel1.Children.Remove(textBlockToSearch); 
     int pos = 2; 
     stackPanel1.Children.Insert(pos - 1, textBlockToSearch); 
    } 
    else 
    { 
     Debug.WriteLine("Could not find TextBlock"); 
    } 

如果你有其他的意圖,就像使用鼠標一次選擇的TextBlock,您可能需要使用不同的技術,就像看到在設計階段在Visual Studio界面中。

希望這會有所幫助。

+0

非常感謝,有沒有其他方式沒有刪除元素並重新插入,爲換位置兩個元素? –

+0

我不確定。根據MSDN文檔,「佈局隊列根據可視化樹中元素的順序進行排序,樹中較高的元素位於隊列的頂部......」http://msdn.microsoft.com/ EN-US /庫/ system.windows.uielement.arrange.aspx。我不會使用Content-property來標識TextBlock,而是使用像Name-property這樣的唯一標識符。如果你想深入這一點,我建議你做更多的研究。 – pdvries

+0

非常感謝,電子郵箱:[email protected] –

3

可以通過跟蹤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