Search code examples
c#wpfxamlcombobox

wpf combobox default selection from itemssource


I have a ComboBox in my WPF application where I display a list of items. Most of the times the first item is the correct choice in the itemssource list, only sometimes on a personal request the item could be changed. Now My combo box loads the list but never shows the first item at selected Item. Can anybody help me please. here's my code.

XAML:

<ComboBox Name="cbxShipTo" TabIndex="0" IsTextSearchEnabled="True" ToolTip="Ship To is a Required Field" MinWidth="200" SelectedIndex="0" IsSynchronizedWithCurrentItem="True" 
IsEditable="False" DisplayMemberPath="ShipToCountyState" SelectedValuePath="ShipToValue">
<ComboBox.SelectedValue>
    <Binding Path="ShipToQAD" Mode="TwoWay">
        <Binding.ValidationRules>
            <common:RequiredValidationRule ErrorMessage="Ship To is a Required Field" />
            <ExceptionValidationRule></ExceptionValidationRule>
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedValue>

Code Behind:

cbxShipTo.ItemsSource = dbLookupService.GetShipToByCustomer(_inspectionListItems[0].CompanyID);
cbxShipTo.SelectedItem = cbxShipTo.Items.GetItemAt(0);

I have values in itemsSource, Selected itme hasa a value too, but never gets displayed on the screen.

Any help is appreciated.


Solution

  • The way I ordinarily do this is by keeping a reference to the currently selected item in the ViewModel. (You should probably be doing this anyway, given that you shouldn't be querying the UI object itself to figure out the user's choice.) Initialize YourSelectedItem to the item you'd like to have appear as selected.

    public List<YourType> YourItems { get; set; }
    public YourType SelectedItem = YourItems[index];
    

    Then bind SelectedItem to the YourItems property.

    <ComboBox ... SelectedItem={Binding YourSelectedItem, Mode=TwoWay} ... />
    

    Anytime the user changes their selection in the ComboBox, the YourSelectedItem property will automatically be brought up to date.

    You shouldn't need to use anything else other than SelectedItem.