gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:13:10 25 4
gpt4 key购买 nike

我正在尝试从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com