C# 将图像添加到 wpf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12025721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Image to wpf
提问by Tanuj Wadhwa
I want to add an Imagedynamically to the wpf application.
我想Image动态地向 wpf 应用程序添加一个。
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.
现在,我的问题是如何在不丢失应用程序现有控件的情况下将图像添加到内容中。
采纳答案by Clemens
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 Sourceproperty of this control in code.
当您要动态加载和显示图像时,您仍然需要考虑应用程序的布局。我建议在 XAML 中添加一个(最初为空的)图像控件(例如在网格中),然后Source在代码中设置此控件的属性。
<Grid>
... other controls ...
<Image Name="img" Grid.Row="..." Grid.Column="..."
Width="100" Height="100" Margin="100,100,0,0"/>
</Grid>
Set Sourcein code:
Source在代码中设置:
var uri = new Uri("pack://application:,,,/MyFirstWPF;component/Images/tt.jpg");
img.Source = new BitmapImage(uri);
回答by S3ddi9
by default the window content is a grid so try
默认情况下,窗口内容是一个网格,所以试试
(this.Content as Grid).Children.Add(img);

