How to get next sibling of the item in databound items control?
How to get next sibling of the element in visual tree? This elment is dataitem of the databound ItemsSource. My goal is开发者_开发问答 get acces to sibling in code (assume that i have access to the element itself) and then use BringIntoView.
Thanks.
For example, if your ItemsControl
is a ListBox
, the elements will be ListBoxItem
objects. If you have one ListBoxItem
and you want the next ListBoxItem
in the list, you can use the ItemContainerGenerator
API to find it like this:
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;
}
Here's some sample XAML:
<Grid>
<ListBox Name="listBox">
<ListBoxItem Name="item1">Item1</ListBoxItem>
<ListBoxItem Name="item2">Item2</ListBoxItem>
</ListBox>
</Grid>
and the code-behind:
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));
}
which results in:
This also works if the ItemsControl
is data-bound. If you only have the data item (not the corresponding user interface element), you can use the ItemContainerGenerator.ContainerFromItem
API to get the initial sibling.
精彩评论