简体   繁体   English

C# Windows Forms 应用:更改控件所有实例的行为

[英]C# Windows Forms Application: Change behavior of all instances of a control

I would like to change the increment values and decimal places for all of my numeric updowns.我想更改我所有数字上调的增量值和小数位。

I know I can do this individually with我知道我可以单独使用

numericUpDownName.DecimalPlaces = 2; and numericUpDownName.Increment = 0.01M;numericUpDownName.Increment = 0.01M;

What is the best approach to do this efficiently?有效执行此操作的最佳方法是什么? I could create methods in Form1.cs for each numeric updown but that seems pretty bulky.我可以在 Form1.cs 中为每个数字上下创建方法,但这看起来很笨重。

I tried creating a subclass that inherits numeric updowns but I'm still not sure how I can utilize it to make all the controls work the same way without having to initialize each numeric updown as member of that class in Form1.cs. 我尝试创建一个继承数字 updowns 的子类,但我仍然不确定如何利用它使所有控件以相同的方式工作,而不必将每个数字 updown 初始化为 Form1.cs 中的 class 的成员。

class numberInput : NumericUpDown { }

这就是我正在处理的,其中大部分将隐藏在实际用例中,max case

How are you creating all those NumericUpDown controls?您如何创建所有这些NumericUpDown控件? If you're doing it in the designer, then that's the place to set the properties to what you want.如果您在设计器中执行此操作,那么就是将属性设置为所需内容的地方。

If you're creating them programmatically, then change the properties there instead.如果您以编程方式创建它们,则改为更改那里的属性。

If for some reason you can't do either of those things (but why?) then you could use reflection to set them all like so.如果由于某种原因你不能做这些事情中的任何一个(但为什么?)那么你可以使用反射来设置它们。 This method assumes that it will be a member of the form containing the NumericUpDown controls, and that the controls are all at the top level (ie not contained in a Panel or other such container control):此方法假定它将成为包含NumericUpDown控件的窗体的成员,并且控件都位于顶层(即不包含在Panel或其他此类容器控件中):

void setNumericUpDownProperties()
{
    foreach (var numericUpDown in this.Controls.OfType<NumericUpDown>())
    {
        numericUpDown.DecimalPlaces = 2;
        numericUpDown.Increment = 0.01M;
    }
}

(This requires using System.Linq; ) (这需要using System.Linq;

You would call that after the call to InitializeComponent() in the form's constructor.您可以在调用窗体的构造函数中的InitializeComponent()之后调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM