Windows フォーム デザイナーが null 許容プロパティを持つコントロールによって混乱する

StackOverflow https://stackoverflow.com/questions/56521

  •  09-06-2019
  •  | 
  •  

質問

C# .NET に「数値テキストボックス」があります。これはテキストボックスの派生にすぎず、ユーザーが数値以外を入力しないようにするためのロジックが追加されています。この一環として、次のタイプの Value プロパティを追加しました。 double? (または Nullable<double>)。ユーザーが何も入力しない場合をサポートするために、null を許容します。

このコントロールは実行すると正常に機能しますが、Windows フォームの設計者はこのコントロールの扱いをあまり好んでいないようです。コントロールがフォームに追加されると、次のコード行が InitializeComponent() で生成されます。

this.numericTextBox1.Value = 1;

「値」は型であることに注意してください Nullable<double>. 。これにより、デザイナーでフォームを再度開こうとすると、次の警告が生成されます。

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

その結果、その行を手動で削除して再構築するまで、フォームはデザイナーで表示されません。その後、変更を保存するとすぐにフォームが再生成されます。迷惑な。

助言がありますか?

役に立ちましたか?

解決

または、デザイナーにコードをまったく追加したくない場合は...これをプロパティに追加します。

[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);
    }
}

次に、それを使用して適用する必要があります デザイナーシリアライザー クラスの属性。

の設定に役立つでしょうか? デフォルト値属性 そのプロパティを新しい Nullable(1) に追加しますか?

[DefaultValue(new Nullable<double>(1))]  
public double? Value ...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top