Pregunta

Quiero que ListBoxItem active dos eventos que puedo detectar del UserControl exterior que contiene el ListBox. Esto es lo que tengo hasta ahora:

<ListBox 
            Background="Black"
            Selected="listbox_selected"
            x:Name="listBox">

            <ListBox.Resources>
                <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}" 
                         Value="True">
                            <Setter Property="IsSelected" Value="True" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListBox.Resources>
        </ListBox>

Ahora, esto llama a mi evento ListBox_Selected. Lo que quiero es llamar a un evento o propiedad diferente cuando se mueve. Solo para dejarlo claro, sé cómo cambiar el fondo/primer plano u otras propiedades del propio ListBoxItem. Pero quiero cambiar algo del abuelo.

¿Fue útil?

Solución

Ya tienes ese evento ... manejar un evento enrutado estático desde ListBoxItem clase llamada "seleccionado" (y también hay "no seleccionado") en cualquier antepasado, siempre que no manejemos el evento "Selección" en cualquier parte del árbol de descendientes ...

  <Window x:Class="...."
          ...
          ListBoxItem.Selected="OnListBoxSelected">  
   <Grid>
      <ListBox ItemsSource="{Binding Employees}"
               DispalyMemberPath="Name"
               selectedValuePath="ID" >
        <ListBox.Resources>
            <Style TargetType="ListBoxItem"
                   BasedOn="{StaticResource
                                {x:Type ListBoxItem}}">
                <Style.Triggers>
                   <DataTrigger Binding="{Binding IsMouseOver,
                                            RelativeSource={RelativeSource
                                              Self}}"
                                Value="True">
                         <Setter Property="IsSelected"
                                 Value="True" />
                  </DataTrigger>
               </Style.Triggers>
           </Style>
       </ListBox.Resources> 
      </ListBox>
   </Grid>
 </Window>

Y en código detrás ...

    private void OnListBoxSelected(object sender, RoutedEventArgs e)
    {
        var window = sender as Window;
        var listBoxItem = e.OriginalSource as ListBoxItem;
        var selectedItem = listBoxItem.DataContext;
    }

Espero que esto ayude...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top