例として次のコードを見てみましょう。
public enum ExampleEnum { FooBar, BarFoo }
public class ExampleClass : INotifyPropertyChanged
{
private ExampleEnum example;
public ExampleEnum ExampleProperty
{ get { return example; } { /* set and notify */; } }
}
プロパティ ExampleProperty を ComboBox にデータバインドして、オプション "FooBar" と "BarFoo" を表示し、TwoWay モードで動作するようにしたいと思います。最適な ComboBox 定義は次のようになります。
<ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" />
現在、手動でバインディングを実行するウィンドウに、ComboBox.SelectionChanged イベントと ExampleClass.PropertyChanged イベントのハンドラーがインストールされています。
もっと良い方法や標準的な方法はありますか? 通常はコンバーターを使用しますか? また、ComboBox に適切な値を入力するにはどうすればよいでしょうか? 現時点では i18n を使い始める気すらありません。
編集
つまり、1 つの質問に対する答えが見つかりました。ComboBox に正しい値を入力するにはどうすればよいですか。
静的 Enum.GetValues メソッドから ObjectDataProvider を介して Enum 値を文字列のリストとして取得します。
<Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="ExampleEnumValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="ExampleEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
これを ComboBox の ItemsSource として使用できます。
<ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
ベストアンサー1
カスタム マークアップ拡張機能を作成できます。
使用例:
enum Status
{
[Description("Available.")]
Available,
[Description("Not here right now.")]
Away,
[Description("I don't have time right now.")]
Busy
}
XAML の先頭:
xmlns:my="clr-namespace:namespace_to_enumeration_extension_class
その後...
<ComboBox
ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}"
DisplayMemberPath="Description"
SelectedValue="{Binding CurrentStatus}"
SelectedValuePath="Value" />
そして実装は...
public class EnumerationExtension : MarkupExtension
{
private Type _enumType;
public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
EnumType = enumType;
}
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return;
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum.");
_enumType = value;
}
}
public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
public class EnumerationMember
{
public string Description { get; set; }
public object Value { get; set; }
}
}