【问题标题】:How to display a PictureBox from behind code in C#如何在 C# 中从代码后面显示图片框
【发布时间】:2012-12-18 01:19:51
【问题描述】:

我知道我的问题听起来很基本,但是我到处搜索却一无所获。 这是我的代码:

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

}

这是附加函数:

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 属性。

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

【问题讨论】:

  • newMap.grid 是什么类型?
  • 这也是 winforms 或 wpf,您已将其标记为 Wpf,但使用的是 Winforms 控件并使用 Winforms System.Drawing Methods
  • newMap.grid 是一个自定义类,在这里并不真正相关。但它包含如上所示的“afficher”方法
  • 可能是这样,但我的第二个问题是相关的。
  • 哦,抱歉,没看到。该项目以 WPF 为重点,但我打算使用实际使用图片框和 winforms 的 DrawImage(我猜?)

标签: c# wpf picturebox system.drawing drawimage


【解决方案1】:

由于您使用的 PictureBox 是 Winforms 控件,您需要将 WindowsFormsHost Control 添加到您的 Wpf 表单并将 PictureBox 添加到其中。每当您动态创建控件时,都需要将其添加到 Form 或 Container 对象中,否则将不会显示。

但首先,添加这些引用:

System.Windows.Forms
WindowsFormsIntegration

现在编写类似这样的代码。

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

【讨论】:

  • hm 它说它找不到 WindowsFormsHost 类型。我正在研究以找出缺少的东西。
  • @AdrienBrunelat 它应该是您添加到 Wpf 表单的 Wpf 工具箱中的一个控件。
  • 确实如此,它会自动添加我缺少的参考。谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
相关资源
最近更新 更多