Q: How can I bind a property of type Enum (of any kind) to a ComboBox or ListBox controls?
I bet that you Googled this question more than once. Did you find the correct answer?
Well, I saw a lot of them, with code or XAML only, sorted, filtered, grouped, etc.
With all the respect, I didn't get a generic answer with a two-way data-flow to a single enum-type property.
See these links as an example:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2430540&SiteID=1
http://joshsmithonwpf.wordpress.com/2007/06/20/displaying-sorted-enum-values-in-a-combobox/
http://www.codeproject.com/KB/WPF/FillComboboxWSortedEnum.aspx?print=true
http://blogs.msdn.com/wpfsdk/archive/2007/02/22/displaying-enum-values-using-data-binding.aspx
These are all great solutions for how to display a specific Enum value, but not to bind to a property of any-type of Enum (the type of the enum you want to bind to is not always known at design time, so you can't use the specific type such as the AlignmentValues in the last link).
A: You can bind a property of type Enum (of any kind) to a ComboBox or ListBox controls by using a simple Value Converter and two Binding expressions as follows:
public class EnumTypeConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Enum.GetValues(value.GetType());
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
<ComboBox ItemsSource="{Binding Path=Sign, Converter={StaticResource enumConverter}}"
SelectedValue="{Binding Path=Sign}" />
Download the code from here.