Creating an image+text button with a control template?

Define a CustomControl like this

in .cs

public class MyButton : Button
{
    static MyButton()
    {
       //set DefaultStyleKeyProperty
    }   

    public ImageSource ImageSource
    {
        get { return (ImageSource)GetValue(ImageSourceProperty); }
        set { SetValue(ImageSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ImageSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ImageSourceProperty =
        DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(MyButton), new UIPropertyMetadata(null));
}

in generic.xaml of themes folder

<Style TargetType="{x:Type MyButton}">
    <Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type MyButton}">
            <StackPanel Height="Auto" Orientation="Horizontal">
                <Image Source="{TemplateBinding ImageSource}" Width="24" Height="24" Stretch="Fill"/>
                <TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Left" Foreground="{DynamicResource TaskButtonTextBrush}" FontWeight="Bold"  Margin="5,0,0,0" VerticalAlignment="Center" FontSize="12" />
            </StackPanel>
        </ControlTemplate>
    </Setter.Value>
    </Setter>
</Style>

Leave a Comment