如何从后面的C#代码显示一个图片(How to display a PictureBox from

2019-08-05 10:57发布

我知道我的问题听起来简单,但我找遍了所有的地方,没有发现任何..这是我的代码:

public MainWindow()
{
    InitializeComponent();

    Map newMap = new Map();
    newMap.setMapStrategy(new SmallMapStrategy());
    newMap.createMap();


    System.Windows.Forms.PictureBox pictureBox1 = new System.Windows.Forms.PictureBox();
    pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(newMap.grid[3].afficher);

}

这是afficher功能:

public override void afficher(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(squareImage, pos_x, pos_y, 50, 50);
}

squareImage是对应于Drawing.Image的属性。 POS_X和POS_Y是定制INT32属性。

我想是在运行我的应用程序以查看图像...

Answer 1:

由于您使用的图片框是一个WinForms控制,您将需要添加一个WindowsFormsHost控件到您的WPF窗体和PictureBox的补充。 任何时候你动态地创建你需要把它添加到窗体或容器对象,否则将不被显示的控制。

即是这样的。

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <WindowsFormsHost Height="175" HorizontalAlignment="Left" Margin="10,10,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="255" />
    </Grid>
</Window>

MainWindow.xaml.cs

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            System.Windows.Forms.PictureBox picturebox1 = new System.Windows.Forms.PictureBox();
            windowsFormsHost1.Child = picturebox1;
            picturebox1.Paint += new System.Windows.Forms.PaintEventHandler(picturebox1_Paint);
        }

        void picturebox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"C:\Temp\test.jpg");
            System.Drawing.Point ulPoint = new System.Drawing.Point(0, 0);
            e.Graphics.DrawImage(bmp,ulPoint);
        }
    }
}


文章来源: How to display a PictureBox from behind code in C#