c# - 防止 Size 属性在等于默认值时被序列化

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

我正在尝试从 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 构造函数我将 Size 更改为 200x200(也适用于 DefaultValue)所有 MyButton 都获得新的大小。当然,当我在设计模式中更改大小时,它应该被添加到 Designer.cs 并且不受 MyButton 类中以后更改的影响。

虽然,在当前配置中,Size 总是添加到 Designer.cs

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

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

最佳答案

出于某种原因,ControlDesignerPreFilterProperties 中的 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;
    }
}

关于c# - 防止 Size 属性在等于默认值时被序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772849/

相关文章:

c# - 在 C# 中对包含网格控件的列表框进行排序

c# - MissingReferenceException 没有意义

c# - 无法访问文件,因为它正在被另一个进程使用

VB.NET Winforms 菜单项快捷方式覆盖默认快捷方式?

应用程序失去和获得焦点的 .NET 事件

C# 应用程序在 Windows CE 中崩溃

c# - 如何使用 OrmLite 固定大小而不是 null varchar?

c# - 使用 XmlNode 获取当前节点的 InnerText

.net - .Net中如何跨进程共享对象?

c# - 为什么我无法调整表格以适应显示器的尺寸? (Windows 窗体)