Given a WPF Image control, how can I make it bigge

2019-03-01 15:07发布

问题:

I've done this once before but I have forgotten entirely how to do it.

How can I have it so an Image can grow a bit within 3 seconds (so it's smooth) on MouseOver?

回答1:

One way is to handle the MouseEnter and MouseLeave events with triggers, and use them to scale the image up:

<Image Width="100" Height="100" Source="...">
    <Image.RenderTransform>
        <ScaleTransform 
            x:Name="scale" 
            CenterX="50" 
            CenterY="50" 
            ScaleX="1" 
            ScaleY="1" />
    </Image.RenderTransform>

    <Image.Triggers>
        <EventTrigger RoutedEvent="Image.MouseEnter">
            <BeginStoryboard>
                <BeginStoryboard.Storyboard>
                    <Storyboard Duration="0:0:0.2">
                        <DoubleAnimation 
                            Storyboard.TargetName="scale" 
                            Storyboard.TargetProperty="ScaleX" 
                            To="1.5" />
                        <DoubleAnimation 
                            Storyboard.TargetName="scale" 
                            Storyboard.TargetProperty="ScaleY" 
                            To="1.5" />
                    </Storyboard>
                </BeginStoryboard.Storyboard>
            </BeginStoryboard>
        </EventTrigger>

        <EventTrigger RoutedEvent="Image.MouseLeave">
            <BeginStoryboard>
                <BeginStoryboard.Storyboard>
                    <Storyboard Duration="0:0:0.2">
                        <DoubleAnimation 
                            Storyboard.TargetName="scale" 
                            Storyboard.TargetProperty="ScaleX" 
                            To="1" />
                        <DoubleAnimation 
                            Storyboard.TargetName="scale" 
                            Storyboard.TargetProperty="ScaleY" 
                            To="1" />
                    </Storyboard>
                </BeginStoryboard.Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Image.Triggers>
</Image>