I have a combo which is bound to a list of statuses:
public enum Status
{
[Description(@"Ready")]
Ready,
[Description(@"Not Ready")]
NotReady
}
I am using a converter to display the the description of the enum in the combo box, which is based on the example here: https://stackoverflow.com/a/3987099/283787
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return DependencyProperty.UnsetValue;
}
var description = GetDescription((Enum)value);
return description;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var enumValue = GetValueFromDescription(value.ToString(), targetType);
return enumValue;
}
...
I am binding to the combox box in the view:
<ComboBox
ItemsSource="{Binding Statuses}"
SelectedItem="{Binding SelectedStatus, Converter={StaticResource EnumConverter}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=., Converter={StaticResource EnumConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
My view model contains the following:
public ObservableCollection<Status> Statuses { get; set; } = new ObservableCollection<Status>(new List<Status> { Status.Ready, Status.NotReady });
private Status selectedStatus = Status.Ready;
public Status SelectedStatus
{
get
{
return this.selectedStatus;
}
set
{
this.selectedStatus = value;
this.NotifyPropertyChanged(nameof(this.SelectedStatus));
}
}
Problem
- The combo is empty when the view model displays.
- I am unable to set the
SelectedStatus
from view model, even if I set the bindingMode=TwoWay
.
How do I successfully selected an item in the combo on start up and from the view model?