简体   繁体   中英

Adding Image to wpf

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.

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);

默认情况下,窗口内容是网格,因此请尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM