Question

I want to have ListBoxItem trigger two events which I can catch from the outer usercontrol that contains the ListBox. Here is what I got so far:

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

Now, this calls my listbox_Selected event. What I want is a calling a different event or property when IsMouseOver. Just to make it clear, I know how to change the background/foreground or other properties of the ListBoxItem itself. But I want to change something of the grandparent.

Was it helpful?

Solution

You already have that event... Handle a static routed event from ListBoxItem class called "Selected" (and there is also "UnSelected") at any ancestor, provided that we dont handle "Selection" event anywhere in the descendents tree ...

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

And in code behind ...

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

Hope this helps...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top