使用默认的SelectedIndex将DropDown绑定到Dictionary

时间:2014-11-10 20:01:17

标签: wpf mvvm dropdownbox

我将DropDown绑定到一个静态字典,该字典总是包含n> 0个条目

<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" />

它工作正常,Dropdown已填充且值已存在,如果我选择一个,则会写入Locality属性。

问题是,我想要选择“没有”,但是

SelectedIndex="0"

属性不像我预期的那样有效。

我总是希望在展示时已经选择了第一个项目。

我认为这是某种订单问题,在尝试设置SelectedIndex之后会发生数据绑定吗?

2 个答案:

答案 0 :(得分:0)

您正在选择列表中的第一个项目。 因此,第一个元素位于索引0。

因此,此元素将用作所选项目。

相反,请考虑将所选索引从“0”更改为“-1”。

SelectedIndex="-1"

答案 1 :(得分:0)

好的,我的方式不同,现在可以了。

以前,我有

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

该财产的实施如下:

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

现在我已将其更改为

SelectedValue="{Binding Locality}" />

如果需要,只需填写值:

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;
  }
}
相关问题