Convert Enum to String / String to Enum
October 15th, 2009
I found this today. I need to convert an enumeration into a string list to populate a combobox. I had been looking at converters to do the heavy lifting, but realized that I should do the work in the ViewModel. That simplifies the XAML a bit. While I was typing out code to read the enum values from the settings file Resharper showed me a choice… I could use my custom converter or use the one in the Component Model. Well, I’d rather use the framework solution over a custom solution any day. If nothing else it’s less to test.
Here’s an example from MSDN:
using System.ComponentModel; Enum myServer= Servers.Exchange; string myServerString = "BizTalk"; Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertTo(myServer, typeof(string))); Console.WriteLine(TypeDescriptor.GetConverter(myServer).ConvertFrom(myServerString));
Enjoy,
References:
MSDN EnumConverter Class
http://msdn.microsoft.com/en-us/library/system.componentmodel.enumconverter.aspx

Having learned more, I realized I was working way too hard. The enumeration can and will be converted into a usable object at run time. Just wire it up.
View Model Code:
public Media Media { get; set; } public List<media> MediaList { get { return Enum.GetValues(typeof (Media)).Cast</media><media>().ToList(); } }XAML Code:
<ComboBox x:Name="cbxMedia" ItemsSource="{Binding MediaList}" SelectedItem="{Binding Media}" IsSynchronizedWithCurrentItem="True" />When the user changes selections on the screen, the background value is automatically converted to the correct enum value. I had been thinking that everything had to be converted in to and out of string based objects. Nope. That is not to say that I am using a best practice. I’m still gaining experience with WPF and the M-V-VM pattern.
Of course, the other way to do this would be to express the enumeration as static resource in the XAML. I looked at it. I got it working, then decided that I was breaking too many rules because the View would have to know about the underlying business object. The whole point in M-V-VM is to create ignorant Views. The data context is the only thing the View should know. So no embedded info on business layer objects.
This works and it is simpler. Simpler is always better, but not too simple. To paraphrase Einstein.