2013-01-20 47 views
0

我有一個窗體和一個按鈕在裏面,我如何切換窗口高度,所以當我第一次點擊按鈕時,窗口高度會增加166,當我點擊第二個按鈕時時間,高度將通過166如何切換窗體高度?

對不起,我的問題是愚蠢的,但我真是糊塗降低;由於

private void button2_Click(object sender, EventArgs e) 
    { 

     int FormHeight = this.Height; 
     int FormHeightBefore = FormHeight; 

     if (this.Height == FormHeightBefore) 
     {//toggle off 
      this.Height = this.Height + 166; 
     } 
     else { 
     //toggle on 
      this.Height = this.Height - 166; 
     } 

    } 

我用上面的代碼嘗試,但它不工作,每當我按下按鈕,表格高度仍在增加

回答

1
partial class Form1 { 
    public int FormHeight; 

    private void button2_Click(object sender, EventArgs e) { 
     this.Height += (FormHeight = (FormHeight > 0 ? -1 : 1) * 166); 
    } 
} 
+1

好吧,我想他沒有說答案必須具有良好的可讀性... –

+0

我不知道.. –

+0

不,它會改變自己,但我同意它不太可讀。 –

1

注意您的前兩行:

int FormHeight = this.Height; 
int FormHeightBefore = FormHeight; 

你實際上總是兩個變量設置爲當前高度...

因此同樣if語句總是叫...

這將正常工作:

const int heightOffset = 166; 
int FormHeightBefore = this.Height 
private void button2_Click(object sender, EventArgs e) 
{ 
    if (this.Height == FormHeightBefore) 
    {//toggle off 
     this.Height += heightOffset ; 
    } 
    else 
    { 
     //toggle on 
     this.Height = FormHeightBefore; 
    } 

} 
+0

你忘了;在第一行的結尾......此外,使用「魔術」號碼兩次也不是那麼高雅。 –

+0

@OferZelig我還在編輯答案......修正。 – Blachshma

+0

爲什麼不使用數字166兩次?c @OferZelig –

0

你的代碼失敗,因爲每次你輸入方法(通過按鈕的點擊),它檢查th e 當前形式高度,並認爲它是「最初的一個」。

做這樣的事情:

private readonly int initialHeight; 

public Form1() 
{ 
    InitializeComponent(); 
    initialHeight = this.Height; 
} 

private void button2_Click(object sender, EventArgs e) 
{ 

    if (this.Height == initialHeight) 
    { // increase height 
     this.Height = initialHeight + 166; 
    } 
    else { 
     // decrease height 
     this.Height = initialHeight; 
    } 
} 

注意初始initialHeight聲明您的按鈕的單擊事件的範圍。

+0

常數會更好,然後只是「166」 – Blachshma

+0

不同意,取決於實際使用。如果它僅用於一個地方,並且沒有特別的邏輯含義(即它不代表一個有意義的常量,用英語來描述),那麼它是可以的。 –

+1

你的代碼不起作用,「這個詞在當前上下文中不存在」@OferZelig –

1

你可以做這樣的事情。

bool isExpanded; 

private void button2_click(object sender, EventArgs e) 
{ 
    Height += (isExpanded ? -166 : 166); 

    isExpanded = !isExpanded; 
} 
+0

Buggy,爲什麼是10? –

+1

爲什麼10?爲什麼是166? –

+0

因爲這就是他要求的,你已經改變了他的邏輯...... –