如何在数据绑定项目控件中获取该项目的下一个兄弟?

Ale*_*der 6 c# wpf

如何在视觉树中获得元素的下一个兄弟?这个元素是数据绑定ItemsSource的数据项.我的目标是在代码中访问兄弟(假设我可以访问元素本身),然后使用BringIntoView.

谢谢.

Ric*_*key 6

例如,如果您ItemsControl是 a ListBox,则元素将是ListBoxItem对象。如果您有一个ListBoxItem并且想要ListBoxItem列表中的下一个,您可以使用ItemContainerGeneratorAPI 找到它,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

这是一些示例 XAML:

<Grid>
    <ListBox Name="listBox">
        <ListBoxItem  Name="item1">Item1</ListBoxItem>
        <ListBoxItem Name="item2">Item2</ListBoxItem>
    </ListBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)

和代码隐藏:

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));
}
Run Code Online (Sandbox Code Playgroud)

这导致:

兄弟信息框

如果ItemsControl是数据绑定的,这也有效。如果您只有数据项(而不是相应的用户界面元素),则可以使用ItemContainerGenerator.ContainerFromItemAPI 获取初始同级。