views:

194

answers:

2

Hi,

This should be easy but it's not working. I have a WPF combobox bound to a List.

  • The items populate just fine
  • I want the first item to show on startup.
  • However! If the SelectedIndex is set to 0 or anything else it stays blank.

Wozzup?

Code Result: No item selected when the form loads. :-(

+1  A: 

I think the problem will be that the ComboBox's items are being populated in a background thread (by the binding) and thus at the time you're setting SelectedIndex to 0 there aren't any items in the list.

If that's the case, the trick is to handle the StatusChanged event on the ComboBox's ItemContainerGenerator and set your selected index there:

comboBox1.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
    if (comboBox1.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
    {
        return;
    }

    // unhook the event - we don't need it now
    comboBox1.ItemContainerGenerator.StatusChanged -=
        ItemContainerGenerator_StatusChanged;

    comboBox1.SelectedIndex = 0;
}
Matt Hamilton
Oh dear. Has power superseded simplicity, lol. Thanks for your help. What has to be has to be.
Gregg Cleland
The reason is now apparent: I was creating the object in XAML List<String> and since I didn't know how to populate such an object in XAML I was doing in C#, hence things were out of synch I guess. With creation and population now being done in XAML, setting the SelectedIndex in XAML is works fine. Thanks Matt for the code though. It might come in useful in the future.
Gregg Cleland
(Excuse the grammatical errors above - a result of changing and not checking. Doh.)
Gregg Cleland
A: 

I tend to use ObservableCollection based data types for the DataContext.

ChrisBD