Binding DropDown to Dictionary with default SelectedIndex

210 views Asked by At

I bind a DropDown to a static Dictionary that's always containing n>0 entries

<ComboBox Grid.Row="1" Grid.Column="1" Margin="2,2,2,2" 
    ItemsSource="{Binding Localities}"
    SelectedValuePath="Key"
    DisplayMemberPath="Value"
    SelectedValue="{Binding Locality, Mode=OneWayToSource}"
    SelectedIndex="0" />

And it works just fine, the Dropdown is filled and the values are there and if I select one, the Locality property is written.

Problem is, I do not want to have "nothing" selected, but the

SelectedIndex="0"

property doesn't work as I had expected.

I always want the first item already been selected upon showing.

I assume it's some kind of order problem, that the data binding happens after the SelectedIndex was tried to be set?

2

There are 2 answers

2
Scott Nimrod On

You are selecting the first item within the list. Hence, the first element sits at index 0.

As a result this element will serve as the selected item.

Instead, consider changing the selected index from "0" to "-1".

SelectedIndex="-1"
0
Dee J. Doena On

OK, I did it differently and now it works.

Before, I had

SelectedValue="{Binding Locality, Mode=OneWayToSource}"
SelectedIndex="0" />

And the property was implented as such:

public Object Locality
{
  set
  {
    if(value != null)
    {
      LocalityInternal = (Int32)value;
    }
  }
}

Now I've changed it to

SelectedValue="{Binding Locality}" />

And simply fill in the value if need be:

public Object Locality
{
  get
  {
    if (LocalityInternal == -1)
    {
      return (0); //this is not the index in the combo box but a dictionary key!
    }
    else
    {
      return (LocalityInternal);
    }
  }
  set
  {
    LocalityInternal = (Int32)value;
  }
}