首页 > 解决方案 > Change foreground and background color when hover

问题描述

I have a menu very similar like the image below. The menu items are on the left side of the dashboard panel.

into When I hover over an item, I want to change the item's background and foreground.

The code.

<Border Name="border">

    <Border.Triggers>
        <EventTrigger RoutedEvent="PreviewMouseLeftButtonDown">
            <BeginStoryboard x:Name="MouseDown_BeginStoryboard">
                 <Storyboard>
                      <ColorAnimation Duration="0:0:0" .../><!--Change Background and Foreground  if hover-->
        </EventTrigger>
    </Border.Triggers>
    <Button>
        <Button.Template>
             <ControlTemplate>
                <Grid>
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition />
                         <ColumnDefinition />
                         <ColumnDefinition />
                     </Grid.ColumnDefinitions>
                     <Image Grid.Column="0" Source="SomePlace" />  <!--Change Background and Foreground  if hover--> 
                     <TextBlock Grid.Column="1" Text="Hello" /> <!--Change Background and Foreground  if hover-->
                     <TextBlock Grid.Column="2" Text="World" /> <!--Change Background and Foreground  if hover-->
                </Grid>
             </ControlTemplate>
    </Button>
</Border>

But I don't think ColorAnimation can do it. Maybe ColorAnimationUsingKeyFrames?

标签: wpfxaml

解决方案


这不是完整的答案,但至少它会让你开始

<Button  Height="50" VerticalAlignment="Top">
            <Button.Template>
                <ControlTemplate>
                    <Border x:Name="border1">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>

                            <TextBlock
                                x:Name="txtblock1"
                                Grid.Column="1"
                                Text="Hello" />
                            <TextBlock
                                x:Name="txtblock2"
                                Grid.Column="2"
                                Text="World" />


                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter TargetName="border1" Property="Background" Value="Red" />
                            <Setter TargetName="txtblock1" Property="Foreground" Value="Blue" />
                            <Setter TargetName="txtblock2" Property="Foreground" Value="White" />

                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Button.Template>
        </Button>

推荐阅读