MouseOver で画像の色を変更できる UserControl を作成しました。2 つの SolidColorBrush スタイルを使用して色を切り替え、画像を OpacityMask として表示する四角形があります。
これにより、a) 任意の画像を任意の色にすることができ、b) 新しいボタンが必要になるたびにイベント ロジックを書き直す必要がなくなります。
注: ソースは 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();
}
}
}