问题描述
我有一个包含自定义控件的类库:
I have a class library with a custom control in it:
using System.ComponentModel;
using System.Windows.Forms;
namespace ClassLibrary1
{
public sealed class CustomLabel : Label
{
[DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool AutoSize
{
get => base.AutoSize;
set => base.AutoSize = value;
}
public CustomLabel()
{
AutoSize = false;
}
}
}
注意 AutoSize
在构造函数 和 被覆盖方法的设计器属性中都设置为 false.
Notice that AutoSize
is set to false in both the constructor and the designer attribute on the overridden method.
我有一个要在其中使用控件的 winforms 项目.我从工具箱中拖放它,但它没有将 AutoSize
设置为 false:
I have a winforms project where I want to use the control. I drag/drop it from the toolbox, but it doesn't have AutoSize
set to false:
如果我保存并关闭表单然后重新打开它,现在它已正确设置:
If I save and close the form and then re-open it, now it's set correctly:
如何让它在第一次放在表单上时尊重属性值?
How can I make it respect the property value when first dropped on the form?
推荐答案
您在构造函数中分配的默认值通常会得到尊重.但在某些情况下,默认值将使用设计器进行更改,例如通过控件的 ToolboxItem
的 CreateComponentsCore
方法.
The default values which you assign in constructor are respected in general. But for some cases the default values will be changed using designer, for example by the CreateComponentsCore
method of ToolboxItem
of the control.
Label
的AutoSize
属性的默认值为false
,您甚至不需要覆盖它或在构造函数中设置它.但是一个 AutoSizeToolboxItem
已分配给 Label
,当您删除 的实例时,它会将
.要删除此行为,只需将新的 AutoSize
设置为 true设计师标签ToolboxItem
分配给您的控件即可:
The default value for AutoSize
property for Label
is false
and you even don't need to override it or set it in constructor. But an AutoSizeToolboxItem
has been assigned to Label
which sets AutoSize
to true when you drop an instance of Label
on designer. To remove this behavior, it's enough to assign a new ToolboxItem
to your control:
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
namespace ClassLibrary1
{
[ToolboxItem(typeof(ToolboxItem))]
public sealed class CustomLabel : Label
{
}
}
注意 1: 仅供参考,ToolboxItem
有一个 CreateComponentsCore
方法,您可以在放置时将其用于一些初始化任务设计表面上的控制.
Note 1: Just for your information, the ToolboxItem
has a CreateComponentsCore
method which you can use it to to some initialization tasks when dropping control on design surface.
注意 2 我还要补充一点,CreateComponentCore
方法只会在您将组件从工具箱拖放到设计界面时运行.它描述了为什么在将它放到表单上之后,它会自动调整大小,因为它是在构造函数之后由 CreateComponentCore
设置的.但在你再次打开表单后,这一次,你的构造函数将运行并将属性设置为 false.
Note 2 I should also add, the CreateComponentCore
method will just run when you drop the component from toolbox to design surface. It describes why after dropping it on form, it's auto-size, because it's set by CreateComponentCore
after your constructor. But after you open the form again, this time, just your constructor will run and set the property to false.
这篇关于首次放置在表单上时如何获取要遵守的 WinForms 自定义控件的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!