繁体   English   中英

Windows窗体设计器被具有可为空属性的控件所困扰

[英]Windows Forms Designer upset by a control with a nullable property

我在C#.NET中有一个“数字文本框”,无非就是文本框的派生,还有一些附加的逻辑可以防止用户输入任何非数字的内容。 作为此过程的一部分,我添加了一个double?类型的Value属性double? (或Nullable<double> )。 支持用户不输入任何内容的情况为空。

该控件在运行时工作正常,但是Windows窗体设计器似乎不太喜欢处理它。 当控件添加到窗体时,在InitializeComponent()中生成以下代码行:

this.numericTextBox1.Value = 1;

请记住,“值”的类型为Nullable<double> 每当我尝试在设计器中重新打开表单时,都会生成以下警告:

Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.

结果,在我手动删除该行并重建之前,无法在Designer中查看该表单-此后,一旦保存任何更改,便会重新生成该表单。 烦人。

有什么建议么?

或者,如果您根本不希望设计师添加任何代码,请将其添加到属性中。

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

似乎Visual Studio 2008中存在问题。您应该创建自定义CodeDomSerializer来解决此问题:

public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer
{
    public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
    {
        CodeStatementCollection collection = codeObject as CodeStatementCollection;

        if (collection != null)
        {
            foreach (CodeStatement statement in collection)
            {
                CodeAssignStatement codeAssignment = statement as CodeAssignStatement;

                if (codeAssignment != null)
                {
                    CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;
                    CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;

                    if (properyRef != null && properyRef.PropertyName == "Value" && primitiveExpression != null && primitiveExpression.Value != null)
                    {
                        primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);
                        break;
                    }
                }
            }
        }

        return base.Deserialize(manager, codeObject);
    }
}

然后,应通过在类上使用DesignerSerializer属性来应用它。

将该属性DefaultValue属性设置为新的Nullable(1)有助于吗?

[DefaultValue(new Nullable<double>(1))]  
public double? Value ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM