I don't agree with the two other answers here. There is no need for a grid to be added to wrap the content. The stackpanel is sufficient.
In the xaml add a stackpanel to where you need the content to be.
<StackPanel Name="myStack" Orientation="Horizontal"></StackPanel>
Then in the code behind, like in a button handler or when the window loads add this
Image coolPic = new Image() {
Name="pic",
Source = new BitmapImage(new Uri("pack://application:,,,/images/cool.png")),
Stretch = Stretch.None // this preserves the original size, fill would fill
};
TextBlock text = new TextBlock() {
Name = "myText",
Text = "This is my cool Pic"
};
myStack.Children.Add(coolPic); // adding the pic first places it on the left
myStack.Children.Add(text); // the text would show up to the right
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.
In order for the code to be more useful and or more dynamic you would need a way to change either the text or the image.
So lets say you did want to change those and you go ahead and do a
((TextBlock)FindName("myText")).Text = "my other cool pic";
You would expect the text to be changed but what happens?
Object reference not set to an instance of an object.
Drats but I gave it a name. You would need to add
// register the new control
RegisterName(text.Name, text);
So that you can access the textblock later. This is needed because you added the control to the framework after it was built and displayed. So the final code looks like this after registering the image too
Image coolPic = new Image() {
Name="pic",
Source = new BitmapImage(new Uri("pack://application:,,,/images/cool.png")),
Stretch = Stretch.None // this preserves the original size, fill would fill
};
// register the new control
RegisterName(coolPic.Name, coolPic);
TextBlock text = new TextBlock() {
Name = "myText",
Text = "This is my cool Pic"
};
// register the new control
RegisterName(text.Name, text);
myStack.Children.Add(coolPic);
myStack.Children.Add(text);