Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding an image to a label in wpf?

Tags:

c#

wpf

I am currently developing an application in C# using WPF. What I need to be able to do is on a label make their be an image to the left of the text of the label a small image of an X or a small image of a tick depending on the circumstances. I have got the images included in the project in a folder named images.

How can I assign the images to be placed on the left of the label programatically in the code and not using the XAML code.

like image 355
Boardy Avatar asked Jan 03 '11 16:01

Boardy


People also ask

How do I add an image to a label in XAML?

In the xaml add a stackpanel to where you need the content to be. You can swap the location of the image and the text by adding the text first then the image. If you don't see the image ensure the image's build action is set to resource in the properties window of the image.


2 Answers

You can either group this inside a grid:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>

  <Image Grid.Column="0" Source="{Binding ImageSourceProperty}" />
  <Label Grid.Column="1" Content="{Binding LabelTextProperty}" />
</Grid>

Or, since the label is a content control, you can simply put the image control inside a label control:

<Label>
  <Image Source="{Binding ImageSourceProperty}" />
  My Text
</Label>

Once you know how the xaml should look like, it is very easy to create the same elements via code.

like image 106
Geert van Horrik Avatar answered Sep 24 '22 01:09

Geert van Horrik


Since you want this in code behind and not within XAML I would suggest ditching the Label and using a StackPanel coupled with an Image and TextBlock as seen below where MyGrid could be any container...

        <Grid Name="MyGrid"/>

...then in your code behind...

        StackPanel myStackPanel = new StackPanel();
        myStackPanel.Orientation = Orientation.Horizontal;

        Image myImage = new Image();
        BitmapImage myImageSource = new BitmapImage(); 
        myImageSource.BeginInit();
        myImageSource.UriSource = new Uri("Images/MyImage.png");
        myImageSource.EndInit();
        myImage.Source = myImageSource;

        TextBlock myTextBlock = new TextBlock();
        myTextBlock.Text = "This is my image";

        myStackPanel.Children.Add(myImage);
        myStackPanel.Children.Add(myTextBlock);

        MyGrid.Children.Add(myStackPanel);
like image 32
Aaron McIver Avatar answered Sep 27 '22 01:09

Aaron McIver