ComboBox丢失SelectedIndex

时间:2012-05-24 15:27:14

标签: wpf xaml data-binding mvvm combobox

我遇到一个问题,我的组合框在关闭UserControl时会丢失其SelectedIndex值。 ViewModel仍然拥有它,但视图会将其重置为-1。我理解绑定ItemSource和SelectedIndex的顺序存在问题,但我没有直接绑定到ItemSource。基本上,我试图找出下面绑定的正确语法。

               </ComboBox.ItemTemplate>
                <ComboBox.ItemsSource>
                    <CompositeCollection>
                        <ComboBoxItem IsEnabled="False">Select a database connection...</ComboBoxItem>
                        <CollectionContainer Collection="{Binding Source={StaticResource ConnectionsBridge}}" />
                        <ComboBoxItem>&lt;New...&gt;</ComboBoxItem>
                    </CompositeCollection>
                </ComboBox.ItemsSource>

                **<ComboBox.SelectedIndex>
                    <Binding Path="SelectedConnectionIndex"/>
                </ComboBox.SelectedIndex>**

            </ComboBox>

1 个答案:

答案 0 :(得分:1)

是绑定到索引(int)还是项目(对象)。您的示例绑定到一个指示索引的属性,而不是对象。

您应该设置SelectedIndex绑定的Mode属性

<ComboBox SelectedIndex="{Binding SelectedConnectionIndex, Mode=TwoWay}">
</ComboBox>