我创建了一个 UserControl,它允许您更改 MouseOver 上图像的颜色。有一个矩形使用两种 SolidColorBrush 样式来切换颜色并将图像显示为 OpacityMask。
这 a) 允许您使任何图像成为您选择的任何颜色,并且 b) 照顾您在每次需要新按钮时都必须重写事件逻辑。
注意:Source 必须在代码中设置,因为它不能直接在 XAML 中绑定。
ImageButton.xaml:
<UserControl x:Class="ImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Width="Auto"
Height="Auto"
Cursor="Hand">
<Rectangle x:Name="Border">
<Rectangle.OpacityMask>
<ImageBrush/>
</Rectangle.OpacityMask>
<Rectangle.Style>
<Style TargetType="{x:Type Rectangle}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Fill" Value="{DynamicResource ImageHoverBackground}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="false">
<Setter Property="Fill" Value="{DynamicResource ImageBackground}" />
</Trigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
</UserControl>
ImageButton.xaml.cs:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace MyNamespace
{
public partial class ImageButton : UserControl
{
public static DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSourceChanged));
public ImageSource Source
{
get
{
return (ImageSource)GetValue(SourceProperty);
}
set
{
SetValue(SourceProperty, value);
}
}
private static void OnSourceChanged(DependencyObject Object, DependencyPropertyChangedEventArgs e)
{
ImageButton Button = Object as ImageButton;
var ImageBrush = Button.Border.OpacityMask as ImageBrush;
ImageBrush.ImageSource = Button.Source;
}
public ImageButton()
{
InitializeComponent();
}
}
}