日期:2014-05-17  浏览次数:20853 次

How can I make a set of StackPanels look like several items.
I've got a set of StackPanels. They are named "Item0", "Item1", ..., "Item5".

I'd like to change the Background when mouse over, change back when mouse leave, and keep the highlight color when an item is clicked.

I tried <Style> <Trigger>, it works when mouse over.
XML code

<Style x:Key="ItemStackPanel" TargetType="{x:Type StackPanel}">
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="{StaticResource ResourceKey=HoverItemBrush}"/>
            <Setter Property="Cursor" Value="Hand"/>
        </Trigger>
    </Style.Triggers>
</Style>



Then I add handlers on each StackPanel to handle MouseLeftButtonDown, to make the background permanently changed.
It works too. but after one item is clicked, the mouseover effect doesn't work.
C# code

this.Item0.MouseLeftButtonDown += Item_MouseLeftButtonDown;
this.Item1.MouseLeftButtonDown += Item_MouseLeftButtonDown;
this.Item2.MouseLeftButtonDown += Item_MouseLeftButtonDown;
this.Item3.MouseLeftButtonDown += Item_MouseLeftButtonDown;
this.Item4.MouseLeftButtonDown += Item_MouseLeftButtonDown;
this.Item5.MouseLeftButtonDown += Item_MouseLeftButtonDown;



What should I do?

------解决方案--------------------
XML code

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="WpfApplication1.MainWindow"
    x:Name="Window"
    Title="MainWindow"
    Width="640" Height="480">
    <Window.Resources>
        <Style x:Key="StackPanelStyle1" TargetType="{x:Type StackPanel}"/>
        <Storyboard x:Key="OnMouseEnter1">
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="stackPanel">
                <EasingColorKeyFrame KeyTime="0" Value="Red"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="OnMouseLeave1">
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="stackPanel">
                <EasingColorKeyFrame KeyTime="0" Value="Black"/>
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
    </Window.Resources>
    <Window.Triggers>
        <EventTrigger RoutedEvent="Mouse.MouseEnter" SourceName="stackPanel">
            <BeginStoryboard Storyboard="{StaticResource OnMouseEnter1}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Mouse.MouseLeave" SourceName="stackPanel">
            <BeginStoryboard x:Name="OnMouseLeave1_BeginStoryboard" Storyboard="{StaticResource OnMouseLeave1}"/>
        </EventTrigger>
    </Window.Triggers>

    <Grid x:Name="LayoutRoot">
        <StackPanel x:Name="stackPanel" HorizontalAlignment="Left" Height="60" Margin="105,129,0,0" VerticalAlignment="Top" Width="131" Style="{DynamicResource S