WPF: ComboBox with selecteditem set make not use of SelectedIndex=0?

淺唱寂寞╮ 提交于 2019-12-11 07:53:00

问题


Why is the first element in my combobox popup menu not shown in the selected item area of

my combobox , when I use the SelectedItem binding? Without that it is showing up ?? Using

the same code selecteditem + selectedindex that is no problem!

<ComboBox
        ItemsSource="{Binding SchoolclassSubjectViewModels}"
        SelectedItem="{Binding SelectedSchoolclassSubjectViewModel}"   
        SelectedIndex="0"
        Height="23"
        HorizontalAlignment="Left"
        Margin="375,13,0,0"
        VerticalAlignment="Top"
        Width="151">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding SchoolclassName}" />
                    <TextBlock Text=" " />
                    <TextBlock Text="{Binding SubjectName}" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

Well as workaround I used:

SchoolclassSubjectViewModels.Add(schoolclassSubjectVM);
        SelectedSchoolclassSubjectViewModel = schoolclassSubjectVM;

and this:

SelectedItem="{Binding SelectedSchoolclassSubjectViewModel,Mode=TwoWay}"

but I would prefer the xaml only way as it should really work.


回答1:


It is because the reference inside your ItemsSource collection is not the same as the one in your SelectedItem property. I would venture to guess that you are using one object context to query your database for the list of SchoolclassSubject objects which the ItemsSource is bound to, but another context to query the actual data item to which you bind the SelectedItem. Even though the list contains a reference which represents the value held by your object, it is not really the same reference, but a separate instance of the same data.

There are ways to solve this issue, most of them involve using the SelectedValuePath and SelectedValue instead of the SelectedItem properties, but the concrete solution would be different depending on your particular ORM.



来源:https://stackoverflow.com/questions/2961113/wpf-combobox-with-selecteditem-set-make-not-use-of-selectedindex-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!