Custom button with property as StaticResource
- by alin
I am trying to achieve the following thing: use an svg image into a custom button.
In order to do this I created a Custom button:
public class MainButton : Button
{
static MainButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MainButton), new FrameworkPropertyMetadata(typeof(MainButton)));
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MainButton), new UIPropertyMetadata(""));
public object Image
{
get { return (object)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(object), typeof(MainButton), new UIPropertyMetadata(""));
}
I took a svg file, opened it in inkscape and saved it as xaml file.
I opened Themes.xaml and added the created xaml image as a ControlTemplate
And the button style is:
Style TargetType="{x:Type local:MainButton}"
<StackPanel Canvas.Top="12"
Canvas.Left="0"
Canvas.ZIndex="2"
Width="80">
<ContentControl x:Name="Img" Template="{StaticResource Home}" />
</StackPanel>
<StackPanel x:Name="spText" Canvas.Top="45"
Canvas.Left="1"
Canvas.ZIndex="1"
Width="80">
<TextBlock x:Name="Txt" Text="{Binding Path=(local:MainButton.Text),
RelativeSource ={RelativeSource FindAncestor,
AncestorType ={x:Type Button}}}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Foreground="White"
FontSize="14"/>
</StackPanel>
...
As you can see I have hardcoded the StaticResource name
I want to be able to have a binding with property Image on this Template, something like
So that I can set the Image property of the button with the name of the StaticResource I want.
For example, having beside "Home" image, another one "Back" I would have two buttons in MainWindow declared like this:
Any advice is kindly taken. Thank you for your time.