我有一系列图像,我希望它们都有MouseOver替换。我可以通过以下方式为每个人实现一种风格:
<Image Source="C:\Image1.png" Style="{StaticResource Image1Style}"/>
...
<Image>
<Image.Style>
<Style TargetType="{x:Type Image}" x:Key="Image1Style">
<Setter Property="Source" Value="C:\Image1.jpg"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="C:\Image2.jpg"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
但是这样的实现需要为每个图像设置整个样式块。我宁愿想要一个统一的样式,然后我可以在实际控件的标记中指定IsMouseOver属性,如下所示:
<Image Source="C:\Image1.png" Style="{StaticResource Image1Style}" IsMouseOver="C:\Image1MouseOver.png" />
我以为我正在接触Templating的东西,但是我无法将这些碎片拼凑起来以便完成这项工作。
答案 0 :(得分:3)
将所有图像和绑定图像源的样式写入Tag属性
<Style TargetType="{x:Type Image}" x:Key="Image1Style">
<Setter Property="Source" Value="{Binding Path=Tag,RelativeSource={RelativeSource Self}}"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="{Binding Path=(local:AttachedProperty.AltSource),RelativeSource={RelativeSource Self}}"/>
</Trigger>
</Style.Triggers>
</Style>
<Image Tag="C:\Image1.jpg" local:AttachedProperty.AltSource="C:\Image2.jpg" Style="{StaticResource Image1Style}"/>
并将附加属性写入绑定替代图像源
public class AttachedProperty
{
public static readonly DependencyProperty AltSourceProperty =
DependencyProperty.RegisterAttached("AltSource",
typeof(string), typeof(AttachedProperty),
new PropertyMetadata());
public static string GetAltSource(DependencyObject obj)
{
return (string)obj.GetValue(AltSourceProperty);
}
public static void SetAltSource(DependencyObject obj, string value)
{
obj.SetValue(AltSourceProperty, value);
}
}
答案 1 :(得分:1)
向项目添加新的资源字典,并将其命名为ImageStyles.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:projectName">
<Style TargetType="{x:Type Image}" x:Key="Image1Style">
<Setter Property="Source" Value="C:\Image1.jpg"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="C:\Image2.jpg"/>
</Trigger>
</Style.Triggers>
</Style>
然后,您可以从xaml中将其作为静态资源enter code here
<image style={static resource="Image1Style"} />