2016-07-24 90 views
0

,所以我有一個軟件的時候曾經我點擊一個按鈕時會顯示圖像,但是當我點擊下一步按鈕顯示使先前的圖像假另一個圖像更簡單的方法來清除在VB.Net所有圖像

'When Button1 is clicked do' 
PicBasketball.Visible = True 

'Flase' 
PicBoxing.Visible = False 
PicSoccer.Visible = False 
PicCanoeing.Visible = False 
PicGolf.Visible = False 
PicSwimming.Visible = False 
PicRugby.Visible = False 

只是想知道如果有一個更簡單的方法來做到這一點,而不是設置每個圖像假

+0

爲什麼這個問題被標記爲 – kunz398

回答

3

如果你想在你的窗體的相同位置,以顯示您的圖片(即你的圖片框被放在非常相同的點),你可以得到使用List(Of T)的,並且只使用一個圖片框代替。每個圖像都可以通過索引訪問,您應該將其保存在變量中以跟蹤您當前顯示的圖像。

'Class level (outside any Sub or Function, but inside Public Class). 
Dim Images As New List(Of Image) 
Dim ImageIndex As Integer = 0 

添加圖像:

Images.Add(Image.FromFile("your file path here")) 
'or: 
Images.Add(your image object) 

卸下圖像:

Images.RemoveAt(zero-based index) 

下一張圖片:

ImageIndex += 1 
If ImageIndex >= Images.Count Then ImageIndex = 0 'Going back to the beginning if we're at the last image. 

YourPictureBox.Image = Images(ImageIndex) 

一張圖片:

ImageIndex -= 1 
If ImageIndex < 0 Then ImageIndex = Images.Count - 1 'Going to the last image if we're in the beginning. 

YourPictureBox.Image = Images(ImageIndex) 

事情要記住使用List(Of T)時:

  • 訪問的圖像通過將其索引到列表完成:

    Images(3) 'Returns the fourth (4th) image. 
    
  • 該指數是從零開始的,意思是第一個項目有索引0,第二個索引1等等(如上面的示例索引3 =第四項所示)。

0

做出函數調用SetVisible做到這一點:

  • 接受一個字符串參數調用圖片名稱
  • 遍歷所有的控制,篩選是圖像類型的,並且開始以「產品圖」,並設置visible = False爲所有這些
  • 遍歷所有的控制,篩選是圖像類型的那些,和匹配「PictureName」,並設置visible = True

然後你可以這樣調用:

SetVisible (PicBoxing) 
SetVisible (PicSoccer) 
SetVisible (PicCanoeing) 
-1

添加圖片框的收集將幫助。

Dim myPBs As New List(Of PictureBox) 
Dim curVis As PictureBox 

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown 
    'if ALL of the pictureboxes on the form 
    ' are part of this there is 
    'an easier way, but the long way works 
    myPBs.Add(PictureBox1) 
    myPBs.Add(PictureBox2) 
    myPBs.Add(PictureBox3) 

    For Each pb As PictureBox In myPBs 
     pb.Visible = False 'initial setting 
    Next 

    curVis = myPBs(0) 'show first one 
    Button1.PerformClick() 
End Sub 

Dim ShowPB As Integer = Integer.MaxValue - 1 'which index being shown 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    curVis.Visible = False 
    ShowPB += 1 
    If ShowPB >= myPBs.Count Then 
     ShowPB = 0 'reset 
    End If 
    curVis = myPBs(ShowPB) 
    curVis.Visible = True 
End Sub 
+0

爲什麼這會被低估?它可能不是最優雅的解決方案(迄今爲止沒有答案),但它是一種比原來的解決方案更好的解決方案。 –

+1

我關於SO的主要投訴,沒有評論就投下了投票。 – dbasnett

+0

我完全同意! –

相關問題