My goal is to databind strings that equalivent to my enum.
public enum Language
{
Unknown=0,CSharp=1,VB=2,VisualCpp=3,FSharp=4
}
public enum ProjectType
{
Unknown=0,ConsoleApplication=1,ClassLibrary=2
}
Here's my Model:
class PLanguage
{
public Language EnumLanguage { get; set; }
public string ImagePath { get; set; }
public List<ProjectType> EnumTypes { get; set; }
}
MyViewModel:
class PLanguageViewModel : ViewModelBase
{
public PLanguage PLanguage { get; set; }
private ObservableCollection<string> _typeCollection;
public PLanguageViewModel(PLanguage pLanguage)
{
PLanguage = pLanguage;
}
public ObservableCollection<string> TypeCollection
{
get{} //CAST PLanguage.EnumTypes FROM ENUM TO STRING
}
public string ImagePath
{
get { return PLanguage.ImagePath; }
set
{
if (PLanguage.ImagePath != value)
{
PLanguage.ImagePath = value;
RaisePropertyChanged(() => ImagePath);
}
}
}
public static String ConvertToString(Enum eEnum)
{
return Enum.GetName(eEnum.GetType(), eEnum);
}
}
As you can see, I have a list of enum of type ProjectType. I want to convert these to an observable collection of strings that equalivent to the enum values, so I can databind them easily in my View. I need to create a Dependency Property of that collection, how can I do that?
You can use Enum.GetNames to get all values and ObservableCollection constructor overload for data Binding.
public PLanguageViewModel(PLanguage pLanguage)
{
PLanguage = pLanguage;
_typeCollection = new ObservableCollection<string>(Enum.GetNames(typeof(ProjectType)));
...
}
You can use Enum.Parse to retrieve the ProjectType
from observable collection.
EDIT as per comment
Use following to bind String to SelectItem
. Now You can use DataBinding over SelectedItem
in the view. You can also achieve the same using IValueConverter
private ProjectType _selectedItem'
public string SelectedItem
{
get
{
return ConvertEnumToString(_selectedItem);
}
set
{
_selectedItem = ConvertStringToEnum(value);
}
}
public static string ConvertEnumToString(Enum eEnum)
{
return Enum.GetName(eEnum.GetType(), eEnum);
}
public static ProjectType ConvertStringToEnum(string value)
{
return (ProjectType)Enum.Parse(typeof(ProjectType), value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With