【问题标题】:Dynamically changing image in picture box not working图片框中动态更改图像不起作用
【发布时间】:2016-09-08 21:52:00
【问题描述】:

我已经断断续续地想了好几个星期。

在我的 VB 2010 Forms 应用程序中,我有许多图片框,这些图片框使用拖放方法填充了来自其他图片框的图像。这没问题,它工作正常。图片框都在一个 groupbox 容器中。

问题是试图通过拖放操作在两个图片框之间交换图像。换句话说,pBox1 有 image.x,pBox2 有 image.y。将图像从 pBox2 拖到 pBox1,然后放下;然后 pBox1 将拥有来自 pBox2 的 image.y,而 pBox2 将拥有来自 pBox1 的 image.x。

通过这个例子,这是我到目前为止的代码:

Private Sub pBox2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pBox1.MouseDown
     strImageSource = "pBox2" 'strImageSource is a global string variable
     [other stuff]
 end sub

^ 这会将源图片框的名称保存为全局字符串。

Private Sub pBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles pBox1.DragDrop
    For Each Control as PictureBox in GroupBox1.Controls.OfType(of PictureBox)()
     if Control.Name = strImageSource then
       Control.Image = pBox1.Image
     end if
   next

   dim imgTarget as Image = CType((e.Data.GetData(DataFormats.Bitmap)), Bitmap)
   pBox1.image = imgTarget
 End Sub

^ 这会搜索由 strImageSource ("pBox2") 命名的图片框,并将 pBox1 的内容复制到其中,然后将 pBox2 中的图像放入 pBox1。

我希望这是有道理的。

这会正确地将 pBox2 中的图像放入 pBox1,但不会将图像从 pBox1 切换到 pBox2。 pBox2 只是空白。但是调试显示pBox2中的图像不是什么都没有;它确实包含一个位图。它只是不可见。

现在,作为一个测试,我在 For Each 部分添加了一行来更改图片框的背景颜色:

 For Each Control as PictureBox in GroupBox1.Controls.OfType(of PictureBox)()
   if Control.Name = strImageSource then
     Control.Image = pBox1.Image
     Control.BackColor = color.red
   end if
next

而且背面颜色确实发生了变化。这告诉我 For Each 部分正在工作——它正在找到控件并更改背景颜色。它只是没有显示图像。

有什么我忽略的吗?

谢谢!

【问题讨论】:

  • 我们不知道您在DoDragDrop 中做什么。看起来您使用该全局字符串滚动了自己的方法。

标签: vb.net image visual-studio-2010 picturebox


【解决方案1】:

不要使用strImageSource,而是使用定义为图片框的全局变量

Private tmpPictureBox As PictureBox

然后存储该图片框引用,以便您可以在 DragDrop 上设置其图像

Private Sub pBox2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pBox1.MouseDown
     'store the picturebox reference
     tmpPictureBox = sender
     [other stuff]
 end sub

Private Sub pBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles pBox1.DragDrop
   'set the first image to the second
   tmpPictureBox.Image = sender.image

   'set the second image to the first
   pBox1.image = CType((e.Data.GetData(DataFormats.Bitmap)), Bitmap)
 End Sub

【讨论】:

  • 谢谢,蔡斯。我也想过这个,也试过了,还是不行。我实际上设置了一个临时图片框,并且可以看到图像正在其中显示。它只是不会显示在目标框中。
【解决方案2】:

您应该在 PictureBox 控件上调用 Control.Refresh() 以更新图像。

【讨论】:

【解决方案3】:

好吧,这很愚蠢。

除了一个非常愚蠢的例外,我做的一切都是正确的。在代码的另一部分,莫名其妙地,我在替换图像后清除了内容的图片框。这可能是我试图做的与这个问题无关的事情的残余,我只是从未纠正过。

对此我深表歉意,并感谢所有回复。

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 2011-05-28
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多