我们有一个画布,它有一个带索引器的Children集合。我们提到了其中一个孩子。我们只想让下一个孩子进入名单,如果我们超过了最后一个,我们想再次结束。
我们目前通过循环来获得我们所拥有的索引,然后我们递增,检查边界并在必要时换行,然后使用该结果从索引器中获取子项。。。
但我感觉有三个左边的球要打到我身上。我一定错过了什么。
注意:如果有一个通用的解决方案可以用于任何基于索引的集合,那就太好了,但即使它只是画布特定的,也没关系。
我可能会错过一些东西,但我认为你想要的可以很容易地实现,比如说我有一些类似的XAML
<Canvas x:Name="canv">
<Rectangle x:Name="canvChild1"/>
<Rectangle x:Name="canvChild2"/>
<Rectangle x:Name="canvChild3"/>
<Rectangle x:Name="canvChild4"/>
</Canvas>
然后你所需要的就是获取一个安全的索引(即一个包装的索引),所以假设我有一个第一个元素的句柄,并且想获取下一个,然后是第四个,并且想获得下一个
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Debug.WriteLine(GetSafeElementForIndex(
this.canv.Children.IndexOf(canvChild1)).Name);
Debug.WriteLine(GetSafeElementForIndex(
this.canv.Children.IndexOf(canvChild4)).Name);
}
private FrameworkElement GetSafeElementForIndex(int currentIndex)
{
return (FrameworkElement)this.canv.Children[WrappedIndex(++currentIndex)];
}
private int WrappedIndex(int currentIndex)
{
return currentIndex % this.canv.Children.Count;
}
}
这打印这个:
canvChild2
canvChild1
我认为你也可以使用Colin Eberhardts出色的LINQ到树的东西,这将允许你在视觉树上使用LINQ:http://www.codeproject.com/Articles/62397/LINQ-to-Tree-A-Generic-Technique-for-Querying-Tree
这是非常方便的东西,它允许您像对待XML一样对待VisualTree,并导航不同的轴。
您可能不应该直接使用画布,而应该使用画布为ItemsPanel
的ItemsControl
。您也可以在项目顶部使用CollectionView
,这允许您获取和移动CurrentItem
(MoveCurrentTo*
)。