10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

列挙型の値を対応する文字列で表示したい!

Posted at

背景

  • C# + XAML
  • 列挙の値に対応する文字列を表示したい
「演算子」列挙型
//演算子
public enum Operator
{
  PLUS, MINUS, MULTIPLY, DIVIDE,
}
XAML
<!--演算子-->
<ComboBox ItemsSource="{Binding Path=Operators}" />

ここでは、ComboBoxのItemsSourceを、Operator列挙型のコレクションとバインドしています。

他に何も書かなければ、ComboBoxの選択肢は、列挙の値(PLUSなど)がそのまま文字列として表示されますね。

でも、Operator列挙型は演算子なので、「+」や「-」を表示したいんです!

BindingにConverterを付けると…

まず思いつくのが、バインドにコンバーターを指定する方法です。

XAML
<!--演算子-->
<ComboBox ItemsSource="{Binding Path=Operators,
                                Converter={StaticResource converter}}" />

しかしこれは、バインドしている対象、ここでは「Operator列挙型のコレクション」をコンバートするコンバーターを指定するものです。

これでもいいのですが、コレクションのコンバーターではなく、やっぱり個々のアイテムのコンバーターにしたいですよねぇ。

TypeConverter属性!

そこでTypeConverter属性の登場です!

「演算子」列挙型
//演算子
[TypeConverter(typeof(OperatorConverter))] //コンバーターの指定
public enum Operator
{
  PLUS, MINUS, MULTIPLY, DIVIDE,
}

上記のようにOperator列挙型にTypeConverter属性を付けると、Operator列挙型と他の型とのコンバートが必要になると、指定したクラス(ここではOperatorConverter)がコンバーターとして使われます。

ここで作っているOperatorConverterクラスは列挙型に付けるコンバーターなので、System.ComponentModel.EnumConverterクラスを継承元にして定義します。

OperatorConverterクラス
//演算子と文字列のコンバーター
public class OperatorConverter : System.ComponentModel.EnumConverter
{
  //コンストラクター
  public OperatorConverter(Type type) : base(type)
  {
  }

  //演算子から文字列への変換
  public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  {
    if (destinationType != typeof(string)) throw new NotSupportedException();

    try
    {
      Operator ope = (Operator)value;
      return ope.GetString();//Operatorをstringに変換する拡張メソッド(詳細は省略)
    }
    catch
    {
      throw new NotSupportedException();
    }
  }

  //文字列から演算子への変換
  public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  {
    //(略)
  }
}

ConvertToメソッドに他の型へのコンバート、ConvertFromメソッドに他の型からのコンバート処理を記述します。

XAML
<!--演算子-->
<ComboBox ItemsSource="{Binding Path=Operators}" />

これで、XAMLはもとのままですが、ComboBoxの選択肢はPLUSなど列挙の値そのままではなく、OperatorConverter.ConvertToメソッドで変換した値になりました。

めでたし、めでたし!

参考

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?