2009-11-10 65 views
1

我正在嘗試製作一個具有自定義檢查圖像的「複選框」。當用戶點擊圖片框時,我需要它在選中和取消選中之間切換。我試了下面的代碼,第一次點擊顯示檢查圖像很好,但是第二次點擊什麼都不做。有任何想法嗎?切換PictureBox圖像C#

private void pictureBox7_Click(object sender, EventArgs e) 
    { 
     if (pictureBox7.Image == Image.FromFile(checkedImg)) 
     { 
      pictureBox7.Image = Image.FromFile(uncheckedImg); 
     } 
     else 
     { 
      pictureBox7.Image = Image.FromFile(checkedImg); 
     } 
    } 

回答

4

if說法是錯誤的,因爲它是不太可能回到true因爲你比較,你重新創建每次Image類的實例。你可以這樣修改:

private bool _pbChecked = false; 
private void pictureBox7_Click(object sender, EventArgs e) 
{ 
    var pictureBox = (PictureBox)sender; 
    string imgPath = _pbChecked ? uncheckedImg : checkedImg; 
    pictureBox.Image = Image.FromFile(imgPath); 
    _pbChecked = !_pbChecked; 
}