2

I want to add an Image dynamically to the wpf application.

What I have tried :

            Image img = new Image();
            img.Height = 100;
            img.Width = 100;
            img.Visibility = Visibility.Visible;

            Thickness th = new Thickness(100, 100, 0, 0);
            img.Margin = th;

            string strUri2 = String.Format(@"pack://application:,,,/MyFirstWPF;component/Images/tt.jpg");
            img.Source = new BitmapImage(new Uri(strUri2));

I know, the image won't display unless I add it to the Content.

this.Content=img;

but with this the existing controls(shapes) on the app are lost.

Now, my question is how to add the image to the content without losing existing controls from the app.

3
  • you should add it to your controls container (parent) Commented Aug 19, 2012 at 10:15
  • What is this in this.Content? Commented Aug 19, 2012 at 10:17
  • so what is you first child in visual tree (grid, stackpanel,...) Commented Aug 19, 2012 at 10:22

2 Answers 2

7

When you are going to load and show an image dynamically, you still need to think about the layout of your application. I would suggest to add an (initially empty) Image control in XAML (for example in a Grid), and later set the Source property of this control in code.

<Grid>
    ... other controls ...
    <Image Name="img" Grid.Row="..." Grid.Column="..."
           Width="100" Height="100" Margin="100,100,0,0"/>
</Grid>

Set Source in code:

var uri = new Uri("pack://application:,,,/MyFirstWPF;component/Images/tt.jpg");     
img.Source = new BitmapImage(uri);
Sign up to request clarification or add additional context in comments.

Comments

1

by default the window content is a grid so try

(this.Content as Grid).Children.Add(img);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.