views:

374

answers:

2

I have a ComboBox:

<ComboBox Name="iComponentFieldComboBox" SelectedIndex="{Binding ComponentFieldSelectedIndex, Mode=TwoWay}" Height="23" Margin="132,0,280,38" VerticalAlignment="Bottom">
    <ComboBoxItem Name="item1">item1</ComboBoxItem>
    <ComboBoxItem Name="item2">item2</ComboBoxItem>
    <ComboBoxItem Name="item3">item3</ComboBoxItem>
</ComboBox>

When I start my WPF and set the ComponentFieldSelectedIndex property of my ViewModel in my code, nothing happens. But after I have selected an item in the combobox, then suddenly setting ComponentFieldSelectedIndex does work.

for example:

  • start app.
  • click button that sets ComponentFieldSelectedIndex to 1.
  • selected item doesn't change to item2.
  • select item3 in combo box.
  • click button that sets ComponentFieldSelectedIndex to 1.
  • selected item does change to item2.

Does anyone have an idea what could be causing this?

A: 

Is the ComponentFieldSelectedIndex property on a class that implements INotifyPropertyChanged or is it a DependencyProperty? If it isn't then updates to the property won't be seen by the UI. In other words changing the value in the click handler of the button won't make the combo box change.

Mike Two
My ViewModel implements INotifyPropertyChanged. Remember, after I have changed the selection through the user interface once, everything works fine.
Matthijs Wessels
A: 

Ok, I found the problem, it was a stupid mistake on my side......

There was no problem with WPF or whatever. From a configuration file, I loaded the selected index when the app starts. This would set componentFieldSelectedIndex to 1 instead of setting ComponentFieldSelectedIndex to 1 (watch the capital).

This is how I define my properties:

private int componentFieldSelectedIndex = 0;
public int ComponentFieldSelectedIndex
{
    get {return componentFieldSelectedIndex;}
    set 
    {
        if(componentFieldSelectedIndex == value) return;

        componentFieldSelectedIndex = value;
        OnPropertyChanged(PropertyName.ComponentFieldSelectedIndex);
    }
}

So this would not generate a property changed event because I set the private field directly. So the combo box would still show "item1" (index 0) while componentFieldSelectedIndex was 1. Pressing the reset button would set ComponentFieldSelectedIndex to 1, but because componentFieldSelectedIndex was already 1, it would not generate a property changed event. Until ComponentFieldSelectedIndex would be set to something else (e.g. through the UI) and then everything would be fine again.

So the problem was actually a typo on my part.

Matthijs Wessels
@Matthijs - Glad you found it. Sorry I couldn't help.
Mike Two