I am trying to create an Image Button in WPF. What I have done is
User Control Class
public class ButtonWithImage : Button
{
public ImageSource ButtonImage
{
get { return (ImageSource)GetValue(ButtonImageProperty); }
set { SetValue(ButtonImageProperty, value); }
}
// Using a DependencyProperty as the backing store for ButtonImage. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ButtonImageProperty =
DependencyProperty.Register("ButtonImage", typeof(ImageSource), typeof(ButtonWithImage));
}
Resource Dictionary Code
<Style x:Key="ButtonWithImageStyle" TargetType="complaintRegister:ButtonWithImage">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="complaintRegister:ButtonWithImage">
<StackPanel>
<Image Source="{Binding ButtonImage, RelativeSource={RelativeSource TemplatedParent}}" Width="50" Height="50"/>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
XAML
<complaintRegister:ButtonWithImage x:Name="ButtonAdd" Content="Add New Complaint" Style="{StaticResource ButtonWithImageStyle}"
ButtonImage="Resources\Plus.png"
Width="150" Height="75" Margin="10 0" Command="{Binding NewCommand}">
</complaintRegister:ButtonWithImage>
Error
It does displays the image in design mode, but at runtime throws this exception
Cannot locate resource 'resources/plus.png'
I can't help but thinking it is trying to resolve 'resources/plus.png' instead of 'Resources/Plus.png.
I bet there is a binding error displayed in output window. :)
How about you post us that error message here.
Btw, in such cases its more propriate to use TemplateBinding instead of RelativeSource TemplatedParent.
TemplateBinding is lets say it like this, specified to work well in control's template. :)
Check those links out:
http://msdn.microsoft.com/en-us/library/ms742882(v=vs.110).aspx
http://www.codeproject.com/Tips/599954/WPF-TemplateBinding-with-ControlTemplate
Edit :
Ahhh you are talking about location of your image.
By default, the Image control only recognize compiled resource image when using XAML to specify its Source property. But, we can use converter or custom markup extension to achieve this goal. The following links contain information about data binding converter and markup extension.
Therefore set that png to build action -> resource and rebuild your solution or use this:
<Image>
<Image.Source>
<BitmapImage UriSource="../Relative/Path/To/Image.png" />
</Image.Source>
</Image>
Though if you wish to use MVVM on this and change path based on data I suggest you to use Bindings:
<Image Source="{Binding MyPath}" Height="50"... />