Search code examples
c#wpfcombobox

Why is my combobox failing to bind to my List<string> in my ViewModel? WPF


I have four Comboboxes in my XAML. It looks like this:

 <ComboBox Grid.Row="2" ItemsSource="{Binding VehiclesAvailable}"  DisplayMemberPath="FleetNumber"/>
 <ComboBox Grid.Row="3" ItemsSource="{Binding Employees_VehicleEligible}" DisplayMemberPath="FullName"/>
 <ComboBox Grid.Row="4" ItemsSource="{Binding Jobsites}" DisplayMemberPath="Name"/>
 <ComboBox Grid.Row="5" ItemsSource="{Binding Conditions}" SelectedItem="{Binding SelectedCondition}" />

The first three CBs are bound to ObservableCollection properties, and these work fine. The last is bound to a List, and it is not displaying any content.

In the VM, I declare the property and set its value in a LoadInitialData command.

    //PROPERTIES
    public ObservableCollection<VehicleModel> VehiclesAvailable { get; set; }
    public ObservableCollection<EmployeeModel> Employees_VehicleEligible { get; set; }
    public ObservableCollection<JobsiteModel> Jobsites { get; set; }
    public ConditionsModel Conditions { get; set; }
    public GenericCondition SelectedConditionOut { get; set; }
    public string SelectedCondition { get; set; }

    //COMMANDs
    public RelayCommand<object> LoadIntialDataCommand { get; set; }

    //METHODS
    public async void LoadInitialData(object e)
    {
        var vehiclesAvailable = await GetData.VehiclesAvailableQueryAsync();
        foreach (VehicleModel _vehicle in vehiclesAvailable)
            VehiclesAvailable.Add(_vehicle);
        var employees_VehiclesEligible = await GetData.Employees_VehiclesEligibleQueryAsync();
        foreach (EmployeeModel _employee in employees_VehiclesEligible)
            Employees_VehicleEligible.Add(_employee);
        Conditions = new ConditionsModel();
    } 

And for what it's worth, this is where I define the ConditionsModel:

 class ConditionsModel
    {
        private List<string> _conditions;

        public List<string> Conditions
        {
            get { return new List<string>() { "New", "Excellent", "Good", "Fair", "Poor", "Unacceptable" }; }
            set { _conditions = value; }
        }

When I step through the code, placing a break point at the closing bracket of the LoadInitialData method, Conditions appears to have all the strings populated. And when I go to the XAML, sure enough, all the strings appear when I hover over the ItemsSource property. But when I run it, the combobox is empty. What might be my next step to debug this problem?


Solution

  • The Conditions property that you currently bind to doesn't return an IEnumerable which is required for the ItemsSource property.

    You should bind to the Conditions list property of the ConditionsModel:

    <ComboBox Grid.Row="5" ItemsSource="{Binding Conditions.Conditions}" 
              SelectedItem="{Binding SelectedCondition}" />