简体   繁体   English

如何在C#Winforms中覆盖Control.Enabled属性?

[英]How to override Control.Enabled property in C# Winforms?

I have a custom control I am working on. 我正在使用一个自定义控件。 I want to change its color when it is enabled or disabled. 我要在启用或禁用它时更改其颜色。 So I wrote a code inside OnEnabledChanged . 所以我在OnEnabledChanged里面写了一个代码。

        protected override void OnEnabledChanged(EventArgs e)
        {
            if (!Enabled)
            {
                temp1 = colorOn;
                temp2 = colorOff;
                colorOff = colorOn = Color.LightGray;
            }
            else
            {
                colorOn = temp1;
                colorOff = temp2;
            }
            Invalidate();
            base.OnEnabledChanged(e);
        }

This code works fine in runtime but not design time. 这段代码在运行时很好,但在设计时效果不佳。 It wasn't raised when I changed the Enabled property in design time. 当我在设计时更改Enabled属性时,没有提出它。 So I want to override the Enabled property of the control. 所以我想覆盖控件的Enabled属性。 But it doesn't show up when typing it. 但是键入时不会显示。

So how can I override it? 那么我该如何覆盖呢? If there is another way I want to use it. 如果还有另一种方法,我想使用它。

That is entirely normal. 那是完全正常的。 One job of a control designer is to intercept the behavior of certain properties and methods that interfere with the use of the control in the design view. 控件设计者的一项工作是拦截某些属性和方法的行为,这些行为会干扰设计视图中控件的使用。 The Enabled property is one of them, if that would work at design-time as well then you could never select the control again. Enabled属性就是其中之一,如果它在设计时也能正常工作,那么您将再也无法选择控件。 The designer can't let that happen of course, it always forces Enabled = true at design time and intercepts assignments to the property. 设计人员当然不能让这种情况发生,它总是在设计时强制Enabled = true并拦截对该属性的分配。 As you found out. 如您所知。 Overriding it can work either, it is not a virtual property, but wouldn't give you what you want anyway. 覆盖它也可以工作,它不是虚拟属性,但是无论如何都无法满足您的需求。 The Visible property is another one that's intercepted like that, you can imagine how that goes wrong :) Visible属性是另一个被这样截获的属性,您可以想象这是怎么回事:)

You would have to create your own designer to do something about it. 您将必须创建自己的设计师才能对此进行处理。 This in general tends to be a bazooka to kill a mosquito, especially in this case since you still can't do anything with Enabled. 通常,这往往是杀死蚊子的火箭筒,尤其是在这种情况下,因为使用Enabled仍无法执行任何操作。 And worse, this behavior is implemented by the ControlDesigner class, the kind of class you need as a base class to get a designer going. 更糟糕的是,这种行为是由ControlDesigner类实现的,ControlDesigner类是使设计人员前进所需的基类。 I seriously doubt it is practical. 我严重怀疑这是否可行。

Doing nothing at all to fix this is entirely reasonable, given that none of the other controls in the toolbox change their appearance either when you change their Enabled property in the designer. 完全不采取任何措施来解决此问题是完全合理的,因为在设计器中更改其Enabled属性时,工具箱中的其他控件均不会更改其外观。

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

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