如何在Stackpanel中更改元素的位置?

时间:2012-10-21 10:23:23

标签: wpf

我有一个有5个孩子的Stackpanel。

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

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

如何在运行时更改元素的位置?

2 个答案:

答案 0 :(得分:4)

可以通过跟踪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属性。

我怀疑你是否想要将StackPanel用于此类目的。使用ItemsControl比使用ListBox要容易得多,因为它们可以绑定到T的ObservableCollection。更新绑定集合后,控件也会同样更新。

我希望这会有所帮助。示例代码可以下载here

答案 1 :(得分:0)

这个问题有点不清楚,因为意图没有特别明确。以下代码允许您根据Text-content-property移动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界面中所见。

希望这有帮助。