简体   繁体   English

在WPF图像中显示鼠标上的不同图像

[英]Showing different image on mouse over in WPF Image

I have a datatemplate used for datagridtemplatecolumn 我有一个datatemplate用于datagridtemplatecolumn
I am trying to show different image on mouse over in Image . 我试图在Image上显示鼠标上的不同图像。
On mouse over, the cursor is changing but image is not changing. 鼠标悬停时,光标正在变化,但图像没有变化。

 <DataTemplate x:Key="MyDataTemplate" DataType="DataRowView">
        <StackPanel Orientation="Horizontal" Background="Transparent">
            <Image Margin="0,0,0,0"   Width="50" Height="50" Source="{Binding Converter={StaticResource SetImgToDG}}" ToolTip="{Binding}" >
                <Image.Resources>
                    <Style TargetType="{x:Type Image}">
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <!-- Hover image -->
                                <Setter Property="Cursor" Value="Hand"/>
                                <Setter Property="Source" Value="C:\Images\Coil3.png"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Image.Resources>
            </Image>
        </StackPanel>
    </DataTemplate>  

Is that binding creates the problem?? 这种绑定是否会产生问题?
How to resolve it?? 怎么解决?

Your problem is that the initial source of the image is defined directly on the Source property of the image instance. 您的问题是图像的初始源直接在图像实例的Source属性上定义。

When there are multiple things that try to set the value of a dependency property, the framework has to decide which value to use. 当有多个东西试图设置依赖属性的值时,框架必须决定使用哪个值。

In your case the value is being set directly on the image instance (locally) and also by a Trigger . 在您的情况下,值直接在图像实例(本地)上设置,也由Trigger
The local value will always win in this case, so nothing happens when the Trigger is activated. 在这种情况下,本地值将始终获胜,因此激活Trigger时不会发生任何事情。

If you set the initial value in the style instead, the Trigger will win when it tries to change the image source, and that will make the image change when the mouse hovers over it. 如果您在样式中设置初始值,则Trigger在尝试更改图像源时将获胜,并且当鼠标悬停在图像源上时,将使图像发生变化。

You can read more about how the value of a Dependency Property is being resolved on MSDN . 您可以阅读有关如何在MSDN上解析Dependency Property的值的更多信息。

<Image.Resources>
    <Style TargetType="{x:Type Image}">
        <!-- Set the initial source in the style so the trigger can change it -->
        <Setter Property="Source" Value="{Binding Converter={StaticResource SetImgToDG}}" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <!-- Hover image -->
                <Setter Property="Cursor" Value="Hand"/>
                <Setter Property="Source" Value="C:\Images\Coil3.png"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Image.Resources>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM