0

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

  1. The combo is empty when the view model displays.
  2. I am unable to set the SelectedStatus from view model, even if I set the binding Mode=TwoWay.

How do I successfully selected an item in the combo on start up and from the view model?

Community
  • 1
  • 1
openshac
  • 4,966
  • 5
  • 46
  • 77
  • @mm8 is right. you should not use converter for selected item. However, it does not explain why combobox is empty. It looks like you are binding to wrong datacontext. Check you Ouput window during debugging, whether there are some binding errors. Also make sure DataContext of the ComboBox is set to the ViewModel – Liero Feb 23 '17 at 11:45
  • Side note, `Path=.` pls don't. It looks bad. –  Feb 23 '17 at 15:57
  • 1
    @Will you are quite right, thanks. – openshac Feb 24 '17 at 09:11

1 Answers1

1

Don't use a converter for the SelectedItem binding:

<ComboBox
    ItemsSource="{Binding Statuses}"
    SelectedItem="{Binding SelectedStatus}">
 ...

The SelectedItem property should be bound to a Status source property provided that the ItemsSource property is bound to an ObservableCollection<Status>.

mm8
  • 163,881
  • 10
  • 57
  • 88