0

I have a listbox containing some items that have a template. The items are created at runtime. The template triggers an scale animation when the mouse is hovering over a ListBoxItem. I would like to change the background of the item when the user clicks the item. The code below does not work because I believe the IsMouseCaptured (click) is handled by the listbox selector. Any ideas how I can do this all in XAML code?

<ControlTemplate.Triggers>
        <Trigger Property="IsMouseCaptured" Value="True">
            <Setter TargetName="rec" Property="Fill" Value="Black" />
        </Trigger>    
</ControlTemplate.Triggers>

2 Answers 2

1

When the user clicks an item in a listbox, it is selected, therefor your trigger needs to operate on the IsSelected-Property.

Create a style for your ListBoxItem, put the Trigger on the IsSelected-Property and set that Style as ItemContainerStyle.

2
  • That sounds reasonable to fix the background color if the item is selected. But what I would like to do is set the background color only for as long as the mouse left button is down, i.e., imitating a button behavior. Any ideas?
    – Edgar
    Nov 8, 2010 at 14:48
  • you gotta deselect in the MouseUp EventHandler. Other than that, I see no chance.
    – Falcon
    Nov 9, 2010 at 8:07
0

As Falcon said, you could use events for your task. This can even be done purely in XAML, like this:

<EventTrigger RoutedEvent="MouseDown" >
    <EventTrigger.Actions>                      
        <BeginStoryboard x:Name="ClickBackground">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames 
                    Duration="0" FillBehavior="HoldEnd"
                    Storyboard.TargetName="rec"
                    Storyboard.TargetProperty="Fill">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <SolidColorBrush Color="Black" />
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>                           
                </ObjectAnimationUsingKeyFrames>                                
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="MouseUp" >
    <EventTrigger.Actions>                      
        <StopStoryboard BeginStoryboardName="ClickBackground" />
    </EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave" >
    <EventTrigger.Actions>                      
        <StopStoryboard BeginStoryboardName="ClickBackground" />
    </EventTrigger.Actions>
</EventTrigger>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.