Why is this WPF ComboBox not showing the selected value?

Kishore Kumar picture Kishore Kumar · Jan 22, 2010 · Viewed 19.5k times · Source
<CombobBox x:Name="cbo" 
           Style="{StaticResource ComboStyle1}"
           DisplayMemberPath="NAME"
           SelectedItem="{Binding Path=NAME}"
           SelectedIndex="1">
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <TextBlock Text="{Binding Path=NAME}"/>
      </Grid>
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

In the Window OnLoaded event, I wrote the code to set the ItemsSource:

cbo.ItemsSource = ser.GetCity().DefaultView;

While loading the window I can see that the initially the the first item is loading but at the same time it clears the displayed item. I am stuck in this scenario and any help is appreciated.

Regards

Kishore

Answer

itowlson picture itowlson · Jan 22, 2010

Resetting the ItemsSource will mess up the selection.

Also, you are setting both SelectedItem and SelectedIndex. You want to set only one of these; if you set both, only one will take effect.

In addition, your SelectedItem declaration is probably wrong. SelectedItem="{Binding NAME}" will look for an item which is equal to the value of the NAME property of the ambient (probably Window-level) DataContext. This will work only if the ComboBox.ItemsSource is a list of strings. Since your ItemTemplate works, I assume ComboBox.ItemsSource is actually a list of City objects. But you are telling WPF that the SelectedItem should be a string (a NAME). This string will never be equal to any City object, so the result will be no selection.

So to fix the problem, after setting ItemsSource, set either SelectedItem or SelectedIndex, depending on your requirements and your data model:

cbo.ItemsSource = ser.GetCity().DefaultView;
cbo.SelectedIndex = 1;
// or: cbo.SelectedItem = "Wellington";    // if GetCity() returns strings - probably not
// or: cbo.SelectedItem = City.Wellington; // if GetCity() returns City objects