2016-11-05 192 views
-3

我編程WinForms應用程序,我已經遇到了一個問題:C#鎖定一個Windows窗體控件

我有,例如,數字增減的控制,並按上/下按鈕時,我不不希望它改變,但我想訪問新的值,而不改變控件本身的數量。

我需要以及能夠解開它的一些條件下,因此它看起來就像是:

private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
    { 
     if (!canChange) 
     { 
      int newValue = get_expected_new_value(); 
      doSomeStuff(newValue); 
      //some_code_to_cancel_the_value_change; 
     } 
     else 
     { 
      //allow the change 
      doSomeOtherStuff(); 
     } 
    } 

我該怎麼辦變薄的事情嗎?

+0

您可以將'.Minimum'和'.Maximum'設置爲相同的值。這應該防止使用按鈕或文本框來更改值。 – HABO

+0

是不是有更溫和的方式做到這一點?與最小和最大看起來有點可怕,可能會導致錯誤,加上我需要得到新的期望值,最小和最大解決方案不會幫助我與此... – David

回答

0

您可以使用numericUpDown1Tag屬性來存儲上一個值。 雖然它不是一個特別優雅的解決方案。

感謝:C# NumericUpDown.OnValueChanged, how it was changed?

在你的情況下,它可以是這個樣子:

 private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
     { 
      var o = (NumericUpDown) sender; 
      int thisValue = (int) o.Value; 
      int lastValue = (o.Tag == null) ? 0 : (int)o.Tag; 
      o.Tag = thisValue; 

      if (checkBox1.Checked) //some custom logic probably 
      { 
       //remove this event handler so it's not fired when you change the value in the code. 
       o.ValueChanged -= numericUpDown1_ValueChanged; 
       o.Value = lastValue; 
       o.Tag = lastValue; 
       //now add it back 
       o.ValueChanged += numericUpDown1_ValueChanged; 
      } 
      //otherwise allow as normal 
     } 

Basicaly你存儲在Tag財產最後一次正確的值。 然後你檢查你的條件,並將其設置回最後一個好值。

+0

謝謝!這真的很有用 – David