The easiest way is to create a special control with the Image property:
public class ImageButton : Button { static ImageButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof (ImageButton), new FrameworkPropertyMetadata(typeof (ImageButton))); } public ImageSource Image { get { return (ImageSource)GetValue(ImageProperty); } set { SetValue(ImageProperty, value); } } public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(default(ImageSource))); }
Then you simply create a style for it in generic.xaml and bind to the Image property instead of explicitly setting the image:
<Style x:Key="{x:Type my:ImageButton}" TargetType="{x:Type my:ImageButton}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type my:ImageButton}"> <Grid> <Image Source="{TemplateBinding Image}" Stretch="Fill"/> </Grid> <ControlTemplate.Triggers> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
Then you can simply use it as follows:
<my:ImageButton Image="Image.png" />
If you need more images for different button states, you can add more dependency properties to it.
Another possible approach is to use what I call a “parameterized style” to avoid creating a specific control; see this blog post for details.
source share