// 无效的写法,图片不会被切换 <Image Margin="0,0,0,0" Width="50" Height="50" Source="1.png" > <Image.Resources> <Style TargetType="{x:Type Image}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Source" Value="2.png"/> </Trigger> </Style.Triggers> </Style> </Image.Resources> </Image>
//解决方案: <Image Margin="0,0,0,0" Width="50" Height="50"> <Image.Resources> <Style TargetType="{x:Type Image}"> <Setter Property="Source" Value="1.png"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Source" Value="2.png"/> </Trigger> </Style.Triggers> </Style> </Image.Resources> </Image>
<Window.Resources> <local:SwitchSourceConverter x:Key="SwitchSourceConverter" /> </Window.Resources> <Image> <Image.Resources> <Style TargetType="{x:Type Image}"> <Setter Property="Source" Value="1.png" /> <Setter Property="Width" Value="100" /> <Setter Property="Height" Value="150" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Cursor" Value="Hand" /> <Setter Property="Width" Value="170" /> <Setter Property="Height" Value="200" /> <Setter Property="Source" Value="{Binding Converter={StaticResource SwitchSourceConverter}}" /> </Trigger> </Style.Triggers> </Style> </Image.Resources> </Image>
public class SwitchSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //注意 图片不存在或者出错,会造成不停闪烁,因为鼠标一直在图片上,图片则不停的进行更改Source var path = "3.png"; var uri = new Uri(path, UriKind.RelativeOrAbsolute); //返回以下几种方式都可以 //return new BitmapImage(uri); return path; return uri; BitmapImage image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri(path, UriKind.RelativeOrAbsolute); image.EndInit(); return image; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }