VicR
VicR

Reputation: 11

How to make a combo box display a default item from a list when the window is loaded

I have a WPF applications with a User Control that contains a couple combo boxes. One of the combo boxes is populated and displays the first value because it is bound to an IEnumerable property of enum values. The other is bound to an IEnumerable property of string values. This displays all the choices in the drop down, but does not display a value when it is first loaded. After selecting an option, the user is able to click the clear button, which will remove their selected option, and display the first value in the list until another value is chosen. Is there a way for me to get it to load with the first value already populated as the default value?

User Control:

<ComboBox x:Name="insuranceTypesComboBox" ItemsSource="{Binding Path=InsuranceTypes}" SelectedItem="{Binding Path=FilteredType}" Width="100" />
<ComboBox x:Name="insurancesComboBox" ItemsSource="{Binding Path=Insurances}" SelectedItem="{Binding Path=FilteredPlan}" Width="100"/>

Properties:

    public IEnumerable<string> Insurances
    {
        get
        {
            var insurances = (from i in this.repository.GetInsurance()
                              select i.CompanyName).ToList();
            return insurances.Distinct();
        }
    }

    public IEnumerable<InsuranceType> InsuranceTypes
    {
        get
        {
            return Enum.GetValues(typeof(InsuranceType)) as IEnumerable<InsuranceType>;
        }
    }

Upvotes: 1

Views: 56

Answers (2)

Vishal v
Vishal v

Reputation: 11

To set the default item that is selected, just use (for example):

myComboBox.SelectedIndex = 5;        // set the 6th item in list as selected

or you can use combobox.SelectedValue. Make sure that you don't accidentally trigger the index changed event.

please refer selectedindex_selectedvalue

Upvotes: 1

haldo
haldo

Reputation: 16701

You can select the first item in the combobox by adding SelectedIndex=0 to the xaml. Or try adding UpdateSourceTrigger=PropertyChanged to the selected item binding:

<ComboBox x:Name="insuranceTypesComboBox" 
    ItemsSource="{Binding Path=InsuranceTypes}" 
    SelectedItem="{Binding Path=FilteredType, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
    Width="100"
    SelectedIndex="0" />

Upvotes: 1

Related Questions