是否有方法阻止在C#WindowsForms UserControl中创建数据类项



如果我创建了一个UserControl,要创建和编辑一个数据类的实例,例如C#WindowsForms中的Person(称为PersonControl(,框架会自动在PersonControl.Designer中添加一个Person实例,为属性提供一些默认值,并用这些值填充项控件。这种行为有很多副作用,我想避免。

问题:是否有定义的方法来阻止在UserControl.Designer中创建数据类实例?

我认为您缺少DesignerSerializationVisibility属性。如果您有自定义控件,则添加的每个公共属性都将自动序列化。可以使用此属性禁用属性的序列化。我还建议添加"可浏览"属性,该属性将对设计器隐藏该属性。如果您希望对序列化有更多的控制,就像只想在另一个属性设置为true时进行序列化一样,您可以创建一个特殊的命名方法,然后由设计器使用ShouldSerialize和Reset方法定义默认值来调用该方法。有一本MSDN杂志,里面有很多winform学习资源,其中有一些关于winform内部工作的精华。如果你感兴趣,你可以快速浏览它。我最喜欢的是。用.NET Framework 2.0 创建和托管自定义设计师

很抱歉,我没有提到另一个属性DefaultValue您可以通过以下方式使用该属性。

public partial class PersonEditControl : UserControl
{
[DefaultValue(null)] // This attribute tells the designer if the property value matches what we specified in the attribute(null) it should not store the property value.
public PersonData? Person { get; set; }
public PersonEditControl()
{
InitializeComponent();
}
}

最新更新