問題描述
將圖像加載到面板 (Load image to panel)
I created a folder "images" inside my project. When the function SetImage() is called, i want to take the image from /images/image.jpg and place it on my Panel. The panel declaration on xaml looks like this:
xmlns:my="clr‑namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wf="clr‑namespace:System.Windows.Forms;assembly=System.Windows.Forms"
<my:WindowsFormsHost Name="windowsFormsHost1">
<wf:Panel x:Name="panelWinform" Dock="Fill" />
</my:WindowsFormsHost>
Example that works ti display a control in the panel:
panelWinform.Controls.Clear();
panelWinform.Controls.Add(controlObject);
controlObject.Dock = System.Windows.Forms.DockStyle.Fill;
How can place the picture instead of the controlObject? And what does the .clear() does? Do I need to call it again?
‑‑‑‑‑
參考解法
方法 1:
It would be very easy without WinForms. You might have a Grid or some other Panel:
<Grid x:Name="panel">
</Grid>
and simply add an Image control to the Panel as shown below.
public void SetImage()
{
var uri = new Uri("pack://application:,,,/images/image.png");
var bitmap = new BitmapImage(uri);
var image = new Image { Source = bitmap };
panel.Children.Add(image);
}
The image URI looks like that because I assume that the image file is a resource in your Visual Studio project. See Pack URIs for some details. You may as well use an absolute or relative file path for the URI.