[英]How Do I Stop Visual Studio from Generating Setter Calls in my UserControl?
I have created a couple of controls that inherit from UserControl for my Winform application. 我已经为Winform应用程序创建了一些从UserControl继承的控件。 They both have parameterless constructors, as is required. 根据需要,它们都具有无参数构造函数。 When I drop them onto my main form, I get an error in Visual Studio at design-time where it cannot render the form. 当我将它们放到我的主窗体上时,我在Visual Studio中在设计时遇到错误,它无法呈现窗体。
What I discovered is that, in the form's Designer.cs file, where my control is instantiated, the IDE is placing a line there that calls one of my setters. 我发现的是,在我的控件实例化的表单的Designer.cs文件中,IDE在那里放置了一个调用我的一个setter的行。 BlockKey = 0
. BlockKey = 0
。 Well, the code behind the setter is calling some other code, and quickly a NullReferenceException gets thrown because the form's not running; 好吧,setter背后的代码是调用其他代码,很快就会抛出NullReferenceException,因为表单没有运行; that other code is not prepared to produce anything at that point. 其他代码不准备在那时产生任何东西。
If I manually remove the setter line, the error goes away. 如果我手动删除setter线,则错误消失。 But closing and re-opening, or re-compiling, the IDE puts the line back in again. 但是关闭并重新打开或重新编译,IDE会重新启动该行。 I tried decorating, inside the UserControl, the setter with [DefaultValue(false)]
, thinking this would suppress the design-time call to the setter, but it did not. 我尝试在UserControl中使用[DefaultValue(false)]
装饰,认为这会抑制对setter的设计时调用,但事实并非如此。
How can I get rid of that line in the Designer? 如何摆脱Designer中的那一行? Or am I expected to do write some preventative code inside the setter instead? 或者我希望在setter中写一些预防性代码呢?
You should use the DesignerSerializationVisibilityAttribute
attribute on your property with it set to Hidden
. 您应该在属性上使用DesignerSerializationVisibilityAttribute
属性并将其设置为Hidden
。
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int BlockKey
{
get { return 0; }
set { /* Do something */ }
}
Alternatively if you need more specific logic (ie only serialize in certain conditions) then you must create a function that returns a bool and has a specific name in the format of bool ShouldSerialize*PropertyName*()
或者,如果您需要更具体的逻辑(即仅在某些条件下序列化),那么您必须创建一个返回bool的函数,并具有bool的特定名称: bool ShouldSerialize*PropertyName*()
bool ShouldSerializeBlockKey()
{
return false;
}
(NOTE: I forget whether this function must be public or not...) (注意:我忘记了这个功能是否必须公开......)
What you're looking for is the DesignerSerializationVisibilityAttribute
. 您正在寻找的是DesignerSerializationVisibilityAttribute
。 This controls whether or not the designer will serialize out default values for a particular attribute or not 这可以控制设计器是否将序列化特定属性的默认值
If you specify the properties as Hidden
the designer won't add values for them 如果将属性指定为“ Hidden
则设计器不会为它们添加值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.