ComboBox Data Binding to an Enum in WPF
2018-04-02
There is a little trick when a ComboBox binds to an Enum in WPF. Here we collect 3 ways.
1: List all enum items in XAML file:
In .xaml:
<ComboBox x:Name="cbUnit" SelectedIndex="{Binding UnitType}">
<ComboBoxItem Content="US"/>
<ComboBoxItem Content="Metric"/>
</ComboBox>
In ViewModel:
private int _UnitType;
public int UnitType
{
get
{
return _UnitType;
}
set
{
if _UnitType!= value)
{
_UnitType= value;
NotifyPropertyChanged("UnitType");
}
}
}
2: Use ItemSource and SelectedItem:
Enum:
public enum MyEnum01
{
MyONE,
MyTwo,
MyThree
}
In XAML:
<ComboBox Width="133" Height="25" ItemsSource="{Binding MyList}" SelectedItem="{Binding TestEnumItem}" />
In ViewModel:
private MyEnum01 _testEnumItem;
public MyEnum01 TestEnumItem
{
get { return _testEnumItem; }
set
{
if (value != _testEnumItem)
{
_testEnumItem = value;
NotifyPropertyChanged("TestEnumItem");
}
}
}
public IEnumerable<MyEnum01> MyList
{
get
{
return Enum.GetValues(typeof(MyEnum01)).Cast<MyEnum01>();
}
}
3: Use KeyValuePair:
Consider to use KeyValuePair list to replace the IEnumerable above:
For example:
public ObservableCollection<KeyValuePair><int, string>> ListTags
{
get
{
return GetTags();
}
}
In GetTags you can get Key and Value pairs.
In XAML:
<ComboBox Margin="0" Height="23" Cursor="Hand"
Width="180" Grid.Row="3" ItemsSource="{Binding ListTags}"
DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding Path=TagItem}" >
In ViewModel
private int _tagItem;
public int TagItem
{
get { return _tagItem; }
set
{
_tagItem = value;
NotifyPropertyChanged("TagItem");
}
}