Search code examples
wpfcomboboxdatatemplateselectedvalue

Why is this WPF ComboBox not showing the selected value?


<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


Solution

  • QUICK ANSWER : Set SelectedIndex = 1 from code-behind.

    It seems that the code in XAML executes first (the InitializeComponent() method), which sets SelectedIndex = 1, but ItemsSource is not specified yet! So SelectedIndex won't affect! (And remember, you cannot specify ItemsSource before InitializeComponent())

    So you have to manually set SelectedIndex = 1 after setting ItemsSource.


    You should do like this :

    XAML

                <ComboBox x:Name="cbo"
                          Style="{StaticResource ComboStyle1}">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding Path=NAME}"/>
                            </Grid>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>
    

    Code

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

    Or this:

    XAML

                <ComboBox x:Name="cbo" Initialized="cbo_Initialized"
                          Style="{StaticResource ComboStyle1}">
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding Path=NAME}"/>
                            </Grid>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>
    

    Code

        private void cbo_Initialized(object sender, EventArgs e)
        {
            cbo.SelectedIndex = 1;
        }
    

    Also note that i've removed DisplayMemberPath="NAME" because you cannot set both DisplayMemberPath and ItemTemplate at the same time. And also, use either SelectedItem or SelectedIndex, not both.