Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an image in a WPF button

Tags:

c#

button

image

wpf

I tried this solution:

<Button>     <StackPanel>         <Image Source="Pictures/img.jpg" />         <TextBlock>Blablabla</TextBlock>     </StackPanel> </Button> 

But I can see the image only in the project window, and when I launch the program it disappears.

If I try this:

  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; 

I get a "'System.Windows.Markup.XamlParseException' in PresentationFramework.dll" exception.

What is the solution?

like image 874
Marco Avatar asked Jul 07 '13 19:07

Marco


People also ask

How do I add an image to a button in Visual Studio?

create an image. set the source of the image to the right file of your resources (e.g. a . png file that you included to your project) drag the image over the button. A text shows that asks you to press ALT to replace the text of the button with the image.

What is a StackPanel WPF?

A StackPanel allows you to stack elements in a specified direction. By using properties that are defined on StackPanel, content can flow both vertically, which is the default setting, or horizontally.

What is the meaning of WPF?

WPF, stands for Windows Presentation Foundation is a development framework and a sub-system of . NET Framework. WPF is used to build Windows client applications that run on Windows operating system. WPF uses XAML as its frontend language and C# as its backend languages.


1 Answers

In the case of a 'missing' image there are several things to consider:

  1. When XAML can't locate a resource it might ignore it (when it won't throw a XamlParseException)

  2. 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')

Snippet

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}" /> 
like image 106
Ron.B.I Avatar answered Sep 18 '22 15:09

Ron.B.I