Adding Image to wpf

萝らか妹 提交于 2019-12-13 18:08:57

问题


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.


回答1:


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



回答2:


by default the window content is a grid so try

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


来源:https://stackoverflow.com/questions/12025721/adding-image-to-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!