views:

51

answers:

1

Hello,

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.

A: 

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.

Aviad P.
I use sqlite database with sql pure no ORM.The first paragraph sounds confusing XD.What you said can not be true maybe..., because I just found in my code this:<ComboBox SelectedItem="{Binding SelectedSchoolclass}" SelectedIndex="0" DisplayMemberPath="SchoolclassName" ItemsSource="{Binding Schoolclasses}" />The binding in the viewmodel is the same pattern as in the above code. The difference is the ComboBox itemtemplate I did not define specially.
msfanboy