【问题标题】:Prevent Size property from being serialized when it's equal to default value防止 Size 属性在等于默认值时被序列化
【发布时间】:2018-08-09 17:29:26
【问题描述】:

我正在尝试从 System.Windows.Forms.Button 创建自己的课程

public class MyButton : Button
{

    public MyButton() : base()
    {
        Size = new Size(100, 200);
    }

    [DefaultValue(typeof(Size), "100, 200")]
    public new Size Size { get => base.Size; set => base.Size = value; }
}

我的 Designer.cs 行为有问题 - 默认值无法正常工作。

我希望,当 MyButton 添加到表单时,它的大小为 100x200,但不是通过 Designer.cs 设置的,所以在 MyButton 构造函数中我将大小更改为200x200(也适用于 DefaultValue)所有 MyButton 获得新尺寸。当然,当我在设计模式下更改大小时,它应该被添加到 Designer.cs 中,并且不受以后MyButton 类中的更改的影响。

尽管在当前配置中,Size 总是添加到 Designer.cs。

我尝试了不同的方法(使用 Invalidate() 或 DesignerSerializationVisibility),但没有成功。

当Size 等于DefaultValue 时,我想阻止它被序列化。例如,当它从工具箱拖放到表单时 - 它会立即在设计器中序列化,而我不希望这样 - 仅在我更改大小时序列化。

【问题讨论】:

  • 您的目标是阻止默认大小被序列化吗?
  • Stopping Size 在等于 DefaultValue 时被序列化。例如,当它从工具箱拖放到表单时 - 它会立即在设计器中序列化,而我不希望这样 - 只有在我更改大小时才会序列化。

标签: c# .net winforms custom-controls windows-forms-designer


【解决方案1】:

出于某种原因,ControlDesigner 将PreFilterProperties 中的Size 属性替换为自定义属性描述符,其ShouldSerializeValue 始终返回true。这意味着Size 属性将始终被序列化,除非您使用隐藏作为值的设计器序列化可见性属性来装饰它。

您可以通过恢复原始属性描述符来更改行为:

using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

[Designer(typeof(MyButtonDesigner))]
public class MyButton : Button
{
    protected override Size DefaultSize
    {
        get { return new Size(100, 100); }
    }

    //Optional, just to enable Reset context menu item
    void ResetSize()
    {
        Size = DefaultSize;
    }
}
public class MyButtonDesigner : ControlDesigner
{
    protected override void PreFilterProperties(IDictionary properties)
    {
        var s = properties["Size"];
        base.PreFilterProperties(properties);
        properties["Size"] = s;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2016-10-12
    相关资源
    最近更新 更多