Add an image in a WPF button
In the case of a 'missing' image there are several things to consider:
When XAML can't locate a resource it might ignore it (when it won't throw a
XamlParseException
)-
The resource must be properly added and defined:
Make sure it exists in your project where expected.
-
Make sure it is built with your project as a resource.
(Right click → Properties → BuildAction='Resource')
Another thing to try in similar cases, which is also useful for reusing of the image (or any other resource):
Define your image as a resource in your XAML:
<UserControl.Resources>
<Image x:Key="MyImage" Source.../>
</UserControl.Resources>
And later use it in your desired control(s):
<Button Content="{StaticResource MyImage}" />
Please try the below XAML snippet:
<Button Width="300" Height="50">
<StackPanel Orientation="Horizontal">
<Image Source="Pictures/img.jpg" Width="20" Height="20"/>
<TextBlock Text="Blablabla" VerticalAlignment="Center" />
</StackPanel>
</Button>
In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
Use:
<Button Height="100" Width="100">
<StackPanel>
<Image Source="img.jpg" />
<TextBlock Text="Blabla" />
</StackPanel>
</Button>
It should work. But remember that you must have an image added to the resource on your project!