2

I am working on winrt phone 8.1 project.

I have this combobox.

<ComboBox PickerFlyoutBase.Title=" "  Name="ModelComboBox" x:Uid="ModelComboBox"  DisplayMemberPath="vcModel" IsEnabled="False" />

And just use this code to in selection change event of combo box that is above that combobox.

    private void MakeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (MakeComboBox.SelectedValue != null)
        {
            List<stbModel> Model = CrudOperations.GetModelById((MakeComboBox.SelectedValue as stbMake).siMakeId);
            if (Model != null && Model.Count > 0)
            {
                ModelComboBox.IsEnabled = true;
                ModelComboBox.ItemsSource = Model.OrderBy(x => x.vcModel);
                ModelComboBox.SelectedIndex = 0;
            }
        }
    }

Now problem is that, I don't know why whenever I select first item from that combobox it shows nothing in combo box while if I select any item other than first then it shows in combobox.

I can attach screenshot if you need.

Yawar
  • 1,924
  • 3
  • 29
  • 39
  • I would guess that your `MakeComboBox` has an initial `SelectedIndex` of `0`, then the selection of the first item will not fire the `SelectionChanged` event since the selection didn't change. Just check where you set the `ItemSource` of `MakeComboBox` and that the `SelectedIndex` isn't `0` – Barnstokkr Jul 09 '15 at 09:20
  • If I select anyother item and then again select first item, it still not show any thing. I remove the `ModelComboBox.SelectedIndex = 0;` line and it starts working. I don't know why this is happening. – Yawar Jul 09 '15 at 10:00
  • 1
    Doing UI interaction in code behind makes it hard to maintain and tends to overcomplicate things. Did you consider using the [MVVM pattern](https://msdn.microsoft.com/en-us/library/windows/apps/gg521153(v=vs.105).aspx)? – Kryptos Jul 10 '15 at 09:13

2 Answers2

2

When MVVM is used, then a direct modification of the SelectedIndex property breaks part of the functionality of the binding. Directly setting the SelectedItem property has the same issue.

This is bad, and should be documented, prevented or properly supported by the framework.

However, the only known working solution, that is not an ugly hack, is to bind also the selected item via the ItemsSource object: Binding ComboBox SelectedItem using MVVM

Community
  • 1
  • 1
Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
0

Have you tried setting the value of SelectedIndex? It should be -1 to select first item by default.

Change From: ModelCombox.SelectedIndex= 0;

To: ModelCombox.SelectedIndex= -1;

Aiseduk
  • 108
  • 10