Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get next sibling of the item in databound items control?

Tags:

c#

wpf

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.

like image 782
Alexander Avatar asked Jun 01 '11 01:06

Alexander


1 Answers

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:

Sibling MessageBox

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.

like image 127
Rick Sladkey Avatar answered Nov 10 '22 18:11

Rick Sladkey