如何在可视化树中获取元素的下一个同级元素?此元素是数据绑定ItemsSource的数据项。我的目标是在代码中访问同级(假设我可以访问元素本身),然后使用BringIntoView。
谢谢。
发布于 2011-06-01 10:47:20
例如,如果您的ItemsControl是ListBox,则元素将是ListBoxItem对象。如果您有一个ListBoxItem,并且想要列表中的下一个ListBoxItem,您可以使用ItemContainerGenerator接口来查找它,如下所示:
public static DependencyObject GetNextSibling(ItemsControl itemsControl, DependencyObject sibling)
{
var n = itemsControl.Items.Count;
var foundSibling = false;
for (int i = 0; i < n; i++)
{
var child = itemsControl.ItemContainerGenerator.ContainerFromIndex(i);
if (foundSibling)
return child;
if (child == sibling)
foundSibling = true;
}
return null;
}下面是一些XAML示例:
<Grid>
<ListBox Name="listBox">
<ListBoxItem Name="item1">Item1</ListBoxItem>
<ListBoxItem Name="item2">Item2</ListBoxItem>
</ListBox>
</Grid>和代码隐藏:
void Window_Loaded(object sender, RoutedEventArgs e)
{
var itemsControl = listBox;
var sibling = item1;
var nextSibling = GetNextSibling(itemsControl, sibling) as ListBoxItem;
MessageBox.Show(string.Format("Sibling is {0}", nextSibling.Content));
}这会导致:

如果ItemsControl是数据绑定的,这也是有效的。如果只有具有数据项(没有相应的用户界面元素),则可以使用ItemContainerGenerator.ContainerFromItem获取初始同级。
https://stackoverflow.com/questions/6195339
复制相似问题