Search code examples
c#wpfcombobox

WPF: Why doesn't my ComboBox SelectedItem show?


(This question has been updated)

I have:

  • Window1 - with a DataGrid
  • Window2 - where I create new DataGrid rows
  • Window3 - where I open a DataGrid row as a profile to view its contents

My issue:

When I open Window3, the ComboBox does not display the item I selected in Window2

The ComboBox in Window2 is bound like this:

<ComboBox
      Text="{Binding PropertyName, UpdateSourceTrigger=PropertyChanged}">
         <ComboBoxItem Content="AS">
         </ComboBoxItem>
         <ComboBoxItem Content="ASA">
         </ComboBoxItem>
         <ComboBoxItem Content="ANS">
         </ComboBoxItem>
         <ComboBoxItem Content="EPF">
         </ComboBoxItem>
</ComboBox>

I would prefer to keep it like that, to just hard-code in the items, as there probably won't be any more of them.

When I save it, I go to Window1, and open my freshly saved row.

The DataGrid SelectedItem is bound by property (named "Selected"), which to each object in Window3 (several TextBoxes - these work fine, and one ComboBox - does NOT work!). The ComboBox stores the data I need, but does not display my previous choice as SelectedItem.

The ComboBox in Window3 is bound like this:

<ComboBox
       DataContext="{Binding Path=(viewmodel:LicenseHolderViewModel.Selected)}"
       Text="{Binding PropertyName, UpdateSourceTrigger=PropertyChanged}">
         <ComboBoxItem Content="AS">
         </ComboBoxItem>
         <ComboBoxItem Content="ASA">
         </ComboBoxItem>
         <ComboBoxItem Content="ANS">
         </ComboBoxItem>
         <ComboBoxItem Content="EPF">
         </ComboBoxItem>
</ComboBox>

So, the items show up in the ComboBox, but nothing is selected as default. If I remove the ComboBoxItem from the XAML, the ComboBox is just empty (naturally). I tried adding ItemsSource="{Binding PropertyName}" (..a shot in the dark), and that just added one of the items, split into three (E, P, F), but none of them set as SelectedItem.

There might be worth noting that my framework automatically couples view with the viewmodels, and me having to set another ViewModels property as each of the objects DataContext, might have caused some hick-ups? (I tried testing for that, and I can't confirm if that's the case).


Solution

  • You should bind the Content of the selected ComboBoxItem to a the source property. To do this, you should bind the to the SelectedValue property and also set the SelectedValuePath property:

    <ComboBox
           SelectedValue="{Binding PropertyName, UpdateSourceTrigger=PropertyChanged}"
           SelectedValuePath="Content">
        <ComboBoxItem Content="AS">
        </ComboBoxItem>
        <ComboBoxItem Content="ASA">
        </ComboBoxItem>
        <ComboBoxItem Content="ANS">
        </ComboBoxItem>
        <ComboBoxItem Content="EPF">
        </ComboBoxItem>
    </ComboBox>