EnumDisplayPairクラス
using System;
public class EnumDisplayPair<T> where T : Enum
{
public T EnumValue { get; }
public string DisplayName { get; }
public EnumDisplayPair(T enumValue, string displayName)
{
EnumValue = enumValue;
DisplayName = displayName;
}
}
複数のEnum定義
namespace ComboBoxSample
{
public enum StatusType
{
NotStarted,
InProgress,
Completed,
OnHold
}
public enum PriorityLevel
{
Low,
Medium,
High,
Critical
}
}
ViewModelでの使用例
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ComboBoxSample
{
public class MainViewModel : INotifyPropertyChanged
{
private StatusType _selectedStatus;
private PriorityLevel _selectedPriority;
// Enumと表示名をペアにしたリスト
public List<EnumDisplayPair<StatusType>> StatusList { get; }
public List<EnumDisplayPair<PriorityLevel>> PriorityList { get; }
// 選択されたEnum値
public StatusType SelectedStatus
{
get => _selectedStatus;
set
{
if (_selectedStatus != value)
{
_selectedStatus = value;
OnPropertyChanged();
}
}
}
public PriorityLevel SelectedPriority
{
get => _selectedPriority;
set
{
if (_selectedPriority != value)
{
_selectedPriority = value;
OnPropertyChanged();
}
}
}
public MainViewModel()
{
// StatusType用のリスト
StatusList = new List<EnumDisplayPair<StatusType>>
{
new EnumDisplayPair<StatusType>(StatusType.NotStarted, "未開始"),
new EnumDisplayPair<StatusType>(StatusType.InProgress, "進行中"),
new EnumDisplayPair<StatusType>(StatusType.Completed, "完了"),
new EnumDisplayPair<StatusType>(StatusType.OnHold, "保留中")
};
// PriorityLevel用のリスト
PriorityList = new List<EnumDisplayPair<PriorityLevel>>
{
new EnumDisplayPair<PriorityLevel>(PriorityLevel.Low, "低"),
new EnumDisplayPair<PriorityLevel>(PriorityLevel.Medium, "中"),
new EnumDisplayPair<PriorityLevel>(PriorityLevel.High, "高"),
new EnumDisplayPair<PriorityLevel>(PriorityLevel.Critical, "緊急")
};
// 初期値
SelectedStatus = StatusType.NotStarted;
SelectedPriority = PriorityLevel.Low;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindow.xaml
<!-- Priority ComboBox -->
<TextBlock Text="優先度選択:" Margin="0,10,0,0"/>
<ComboBox ItemsSource="{Binding PriorityList}"
SelectedValue="{Binding SelectedPriority, Mode=TwoWay}"
SelectedValuePath="EnumValue"
DisplayMemberPath="DisplayName" />
<!-- 選択結果の表示 -->
<TextBlock Text="選択されたステータス:" Margin="0,10,0,0" />
<TextBlock Text="{Binding SelectedStatus}" />
<TextBlock Text="選択された優先度:" Margin="0,10,0,0" />
<TextBlock Text="{Binding SelectedPriority}" />
</StackPanel>
</Grid>
実行結果
- Status ComboBox:
ComboBoxに「未開始」「進行中」「完了」「保留中」が表示されます。- 選択すると対応する
StatusTypeのEnum値(例:StatusType.NotStarted)がSelectedStatusにバインドされます。
- Priority ComboBox:
ComboBoxに「低」「中」「高」「緊急」が表示されます。- 選択すると対応する
PriorityLevelのEnum値(例:PriorityLevel.Low)がSelectedPriorityにバインドされます。
- 選択結果表示:
- 下部にEnum値(例:
NotStarted,Low)が表示されます
- 下部にEnum値(例:


コメント