How to get the next sibling of an item in data controls?

How to get the next sibling of an item in a visual tree? This eluent is the dataitem of the ItemsSource database. My goal is to access my sibling in the code (suppose I have access to the element itself), and then use BringIntoView.

Thanks.

+6
source share
1 answer

For example, if your ItemsControl is a ListBox , the items will be ListBoxItem objects. If you have a ListBoxItem and 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 is an XAML example:

 <Grid> <ListBox Name="listBox"> <ListBoxItem Name="item1">Item1</ListBoxItem> <ListBoxItem Name="item2">Item2</ListBoxItem> </ListBox> </Grid> 

and code:

 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)); } 

that leads to:

Sibling messagebox

This also works if the ItemsControl is data bound. If you only have a data item (and not the corresponding user interface element), you can use the ItemContainerGenerator.ContainerFromItem API to get the original brother.

+4
source

Source: https://habr.com/ru/post/889499/


All Articles