2011-06-01 15 views

Respuesta

4

Por ejemplo, si su ItemsControl es un ListBox, los elementos serán objetos ListBoxItem. Si usted tiene uno ListBoxItem y desea que el próximo ListBoxItem en la lista, puede utilizar la API de ItemContainerGenerator encontrar de esta manera:

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

He aquí algunos XAML muestra:

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

y el código- detrás:

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

que se traduce en:

Sibling MessageBox

Esto también funciona si el ItemsControl está vinculado a los datos. Si tiene el tiene el elemento de datos (no el elemento correspondiente de la interfaz de usuario), puede usar la API ItemContainerGenerator.ContainerFromItem para obtener el hermano inicial.

+0

¡Gracias por tomarse el tiempo para obtener una respuesta completa! :) – Alexander

Cuestiones relacionadas