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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With