Here's my enum:
enum Foo
{
[Description("the quick")]
Bar,
[Description("brown fox")]
Baz,
[Description("jumped over")]
Qux
}
Here's part of my ViewModel:
class MainWindowViewModel : ViewModelBase
{
public ObservableCollection<RowViewModel> Rows { get { ... } }
}
class RowViewModel : ViewModelBase
{
public String Name { get { ... } set { ... } }
public Foo Foo { get { ... } set { ... } }
}
Here's my XAML:
<DataGrid AutoGeneratingColumn="OnAutoGeneratingColumn" ItemsSource="{Binding Path=Rows}" />
Because MainWindowViewModel.Rows[n].Foo
is an enum, WPF will automatically generate a DataGridComboBoxColumn
with the enum members as combobox drop-down values, so far so good.
I want the combobox to use the [Description("")]
values in the combobox drop-down and display. So I implemented an IValueConverter
. I then added a handler for OnAutoGeneratingColumn
:
private void OnAutoGeneratingColumn(Object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridComboBoxColumn dgCol = e.Column as DataGridComboBoxColumn;
if( dgCol != null && e.PropertyType.IsEnum ) {
Binding binding = new Binding( e.PropertyName );
binding.Converter = EnumDescriptionValueConverter.Instance;
dgCol.TextBinding = binding;
dgCol.SelectedItemBinding = binding;
}
}
Unfortunately this doesn't work: the cells appear empty when they have values and the combobox drop-down contains the original enum values rather than descriptions.
You are working too hard to do this, since the enum is not a changeable item, during the VM construction enumerate the enum and extract the descriptions into a list then bind the control to that list.
Example
Take our enums
The extension method to extract descriptions
The creation of our list of strings
List<string> EnumDescriptions { get; set; }
:For the sake of simplicity I will add it to the page's datacontext so I don't have to path into the list named
EnumDescriptions
.Then on my page I will bind to it directly, since Listbox inheirits the page's datacontext which is the
EnumDescriptions
.The result is:
Note that in an MVVM implementation, most likely the whole VM instance would be the page's data context, so the binding needs to know the property name (its binding
path
) off of the data context/ the VM instance, so useBinding EnumDescriptions
orBinding Path=EnumDescriptions
.