There are a couple of ways in WPF to make an image pop out when moving mouse over it. Of course we want the image to pop out smoothly, so in this quick rundown we're going to use the following animation storyboards:

<!-- This storyboard will make the image grow to double its size in 0.2 seconds -->
<Storyboard x:Key="expandStoryboard">
    <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" 
        To="2" Duration="0:0:0.2" />
    <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" 
        To="2" Duration="0:0:0.2" />
</Storyboard>
<!-- This storyboard will make the image revert to its original size -->
<Storyboard x:Key="shrinkStoryboard">
    <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX" 
        To="1" Duration="0:0:0.2" />
    <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleY" 
        To="1" Duration="0:0:0.2" />
</Storyboard>

One thing worth noticing here is the lack of "From" attribute in animation elements. That's because we want the animation pick up from whatever animation state the image is in to make it smoother. Specifying the beginning value of animation (with e.g. "From='1'" in expandStoryboard) would mean the image growing would always start at its original, not current size.

Triggering storyboards with event handlers

If you like imperative coding, you'll probably rush to implement image's MouseEnter and MouseLeaveevent handlers to trigger the animations. Image declaration would in Xaml look somewhat like this:

<Image Name="image1" Source="Image1.png" 
UIElement.MouseEnter="image_MouseEnter"
UIElement.MouseLeave="image_MouseLeave">

<Image.RenderTransform>
<!-- Initial values we're going to animate -->
<ScaleTransform ScaleX="1" ScaleY="1"/>
</Image.RenderTransform>
</Image>

... complemented with a couple of event handlers:

private void image_MouseEnter(object sender, MouseEventArgs e)
{
Storyboard story = (Storyboard)FindResource("expandStoryboard");
Image image = sender as Image;
image.BeginStoryboard(story);
} private void image_MouseLeave(object sender, MouseEventArgs e)
{
Storyboard story = (Storyboard)FindResource("shrinkStoryboard");
Image image = sender as Image;
image.BeginStoryboard(story);
}

[Both storyboards are declared as resources, hence the use of FindResource method for retrieving them.]

Using Event triggers instead of event handlers

Although there's nothing wrong with the previous method, why not do it all in Xaml? Enter EventTriggers:

<Image Name="image2" Source="Image2.png">
<Image.Triggers>
<EventTrigger RoutedEvent="Image.MouseEnter">
<BeginStoryboard Storyboard="{StaticResource expandStoryboard}" />
</EventTrigger>
<EventTrigger RoutedEvent="Image.MouseLeave">
<BeginStoryboard Storyboard="{StaticResource shrinkStoryboard}" />
</EventTrigger>
</Image.Triggers>
<Image.RenderTransform>
<ScaleTransform ScaleX="1" ScaleY="1"/>
</Image.RenderTransform>
</Image>

Looks better, doesn't it?

Finishing with Property triggers

The third method is very similar to the second, except it uses Property triggers instead of Event triggers. Currently, Property triggers have to be declared within a style:

<Style TargetType ="{x:Type Image}">
    <Setter Property="RenderTransform">
        <Setter.Value>
            <ScaleTransform ScaleX="1" ScaleY="1"/>
        </Setter.Value>
    </Setter> 
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource expandStoryboard}" />
            </Trigger.EnterActions>
            <Trigger.ExitActions>
                <BeginStoryboard Storyboard="{StaticResource shrinkStoryboard}" />
            </Trigger.ExitActions>
        </Trigger>
    </Style.Triggers>
</Style>

Additional benefit of using styles is the ability to reuse/apply them to all elements of specified type within the scope the style is declared in. For example, declaring the above style (together with both storyboards) on the application level would generally make all images within application behave the same way. Unless, of course, some images specify their own styles, overriding this behavior. 
And the image?

<Image Name="image3" Source="Image3.png" />

[Note that specifying RenderTransform on this Image is no longer needed, because it's already set with the Style.]

Three ways to make your WPF images pop out on MouseOver的更多相关文章

  1. Redis on Spark:Task not serializable

    We use Redis on Spark to cache our key-value pairs.This is the code: import com.redis.RedisClient va ...

  2. Odoo Two ways to pop warning infomation

    1. raise ValueError(_('title'),_('message')) 2.raise except_orm(_('title'),_('message'))

  3. WPF中弹出菜单

    在WPF里弹出菜单是用Popup,你那个右键的是上下文菜单(也就是快捷菜单). <Grid> <Button x:Name="BtnPop" Width=&quo ...

  4. Problem of saving images in WPF (RenderTargetBitmap)zz

      To save a visual to an image file need to use RenderTargetBitmap, detail is reference to Save and ...

  5. [WPF系列]-基础系列 Property Trigger, DataTrigger & EventTrigger

    So far, we worked with styles by setting a static value for a specific property. However, using trig ...

  6. [WPF系列]-ListBox

    引言 本文就WPF中的ListBox常用项给以实例代码演示,包括隐蔽属性的设置,Style设置,以及ControlTemplate的自定义.   Listbox平滑滚动 <ListBox Ite ...

  7. (WPF) 基本题

    What is WPF? WPF (Windows Presentation foundation) is a graphical subsystem for displaying user inte ...

  8. WPF的二维绘图(一)——DrawingContext

    DrawingContext比较类似WinForm中的Graphics 类,是基础的绘图对象,用于绘制各种图形,它主要API有如下几种: 绘图API 绘图API一般形为DrawingXXX系列,常用的 ...

  9. 基于<MediaElement>的WPF视频播放器(带部分特效)【2】

    一.前言       上回说到需要做放视频的使用向导,这两天公司里的老司机一直帮我答疑解惑,让这个任务变得挺顺的,真心感谢他们! 这次与[1]中的不同之处在于: (1)播放和暂停按钮集成在<Me ...

随机推荐

  1. [Leet Code]Path Sum II

    此题如果 #1 和 #4 判断分支交换,大集合就会超时(因为每次对于非叶子节点都要判断是不是叶子节点).可见,有时候if else判断语句也会对于运行时间有较大的影响. import java.uti ...

  2. iPhone-获取网络数据或者路径的文件名

    Phone中,在网络中的数据流中提取链接中的文件名称时,有很多方法,这里总结一些. 方法一:最直接. 1     NSString * urlString = @"http://www.ba ...

  3. tengine 的优化

    查服务器CPU的核数 : [root@c01 conf]# grep processor /proc/cpuinfo |wc -l 4 [root@c01 conf]# grep -c process ...

  4. Pycharm 2017.1 激活服务器

    最近发现pycharm激活异常困难 原来的激活码 都不能用了 so 根据网上 教程 自己建了激活服务器 尝试可用服务器 20170504 测试发现 给需要域名 http://www.05nb.com: ...

  5. 每日英语:A Buying Guide to Air-Pollution Masks

    Blue skies were finally visible in the capital on Thursday after the region suffered fromseven strai ...

  6. (转) Lua: 给 Redis 用户的入门指导

    可能你已经听说过Redis 中嵌入了脚本语言,但是你还没有亲自去尝试吧?  这个入门教程会让你学会在你的Redis 服务器上使用强大的lua语言. Hello, Lua! 我们的第一个Redis Lu ...

  7. 【C/C++】一道试题,深入理解数组和指针

    在x86平台下分析下面的代码输出结果 int main(void) { ] = {, , , }; ); ); printf(], *ptr2); ; } &a+1 首先明确,a是一个具有4个 ...

  8. python用zipfile模块打包文件或是目录、解压zip文件实例

    #!/usr/bin/env python # -*- coding: utf-8 -*- from zipfile import * import zipfile #解压zip文件 def unzi ...

  9. ADO对Excel对象进行连接时的 两种方法区别

    在通过ADO对Excel对象进行连接时(此时Excel则认为是一个数据源),需要配置对Excel数据源对应的连接串,这个连接串中包括了Provider信息(其实类似对数据库进行连接操作时,都需要指定连 ...

  10. lateral view

    原文地址:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+LateralView# lateral view用于和spl ...