防止 Size 属性 在等于默认值时被序列化
Prevent Size property from being serialized when it's equal to default value
我正在尝试从 System.Windows.Forms.Button
创建我自己的 class
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
class 中更改的影响。
虽然,在当前配置中,Size 总是添加到 Designer.cs.
我尝试了不同的方法(使用 Invalidate() 或 DesignerSerializationVisibility)但没有成功。
我想阻止 Size
在等于 DefaultValue
时被序列化。例如,当它从工具箱中掉落到表单时 - 它会立即在设计器中序列化,而我不希望那样 - 仅在我更改大小时序列化。
出于某种原因,ControlDesigner
将 PreFilterProperties
中的 Size
属性 替换为自定义 属性 描述符,其 ShouldSerializeValue
始终returns 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;
}
}
我正在尝试从 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
class 中更改的影响。
虽然,在当前配置中,Size 总是添加到 Designer.cs.
我尝试了不同的方法(使用 Invalidate() 或 DesignerSerializationVisibility)但没有成功。
我想阻止 Size
在等于 DefaultValue
时被序列化。例如,当它从工具箱中掉落到表单时 - 它会立即在设计器中序列化,而我不希望那样 - 仅在我更改大小时序列化。
出于某种原因,ControlDesigner
将 PreFilterProperties
中的 Size
属性 替换为自定义 属性 描述符,其 ShouldSerializeValue
始终returns 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;
}
}