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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With