c#锁定一个Windows窗体控件

时间:2016-11-05 20:50:14

标签: c# winforms

我编写了一个winforms应用程序,我遇到了一个问题:

例如,我有一个数字UpDown控件,当按下向上/向下按钮时,我不想让它改变,但我想要访问新值,而不更改控件上的数字本身。

我也需要能够在某些条件下解锁它,所以它看起来像那样:

 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();
        }
    }

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用Tag的{​​{1}}属性来存储最后一个值。 虽然它不是一个特别优雅的解决方案。

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

在你的情况下,它看起来像这样:

numericUpDown1

基本上,您将最后已知的良好值存储在 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 } 属性中。 然后检查条件并将值设置回最后一个良好值。