8

プロパティのエディターとしてドロップダウン リストを作成したいと考えていました。ドロップダウン リストのエントリとして文字列しかない場合、これは問題なく機能します (StringConverter を使用)。ただし、文字列の代わりにオブジェクトのリストを使用しようとすると、これは機能しません (ただし、通常のコンボボックスではどのように機能するかに注意してください!) これが私のコードです:

    public static List<Bar> barlist;
    public Form1()
    {
        InitializeComponent();
        barlist = new List<Bar>();
        for (int i = 1; i < 10; i++)
        {
            Bar bar = new Bar();
            bar.barvalue = "BarObject " + i;
            barlist.Add(bar);
            comboBox1.Items.Add(bar);
        }
        Foo foo = new Foo();
        foo.bar = new Bar();
        propertyGrid1.SelectedObject = foo;
    }

    public class Foo
    {
        Bar mybar;

        [TypeConverter(typeof(BarConverter))]
        public Bar bar
        {
            get { return mybar; }
            set { mybar = value; }
        }
    }

    public class Bar
    {
        public String barvalue;
        public override String ToString()
        {
            return barvalue;
        }
    }


    class BarConverter : TypeConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(barlist);
        }
    }

結果(フォームなどに埋め込まれた)は次のようになりました。

ここに画像の説明を入力

エントリをクリックすると、次のようになりました。

ここに画像の説明を入力

(ドイツ語のテキストについては申し訳ありません。変更できるかどうかわかりません。VS は英語ですが、OS は英語ではありません。エラー メッセージは次のとおりです。

  Invalid property value.

  The object of type "System.String" cannot be converted to type 
  "XMLTest.Form1+Bar".

文字列を Bar オブジェクトに変換する後方変換ツールを定義することで、これを回避できると確信しています。これを適切に機能させるには、キーが異なる必要があります。これを行うより良い方法はありますか?propertyGrid コントロールに埋め込まれているコンボ ボックスが文字列を使用するのはなぜですか (通常のコンボ ボックスでは、これを処理するのに何の問題もありません)。

その上、プログラムで中間区切りの位置を変更できますか? 私はまだそのオプションを見つけていません。

ありがとうございました。

4

1 に答える 1

6

CanConvertFromandConvertFromメソッドを変換クラスに追加しました。

class BarConverter : TypeConverter
{
  public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
  {
    return true;
  }

  public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
  {
    return new StandardValuesCollection(barlist);
  }

  public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  {
    if (sourceType == typeof(string))
    {
      return true;
    }
    return base.CanConvertFrom(context, sourceType);
  }

  public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
  {
    if (value is string)
    {
      foreach (Bar b in barlist)
      {
        if (b.barvalue == (string)value)
        {
          return b;
        }
      }
    }
    return base.ConvertFrom(context, culture, value);
  }
}
于 2013-01-29T23:06:14.617 に答える