开发者

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

开发者 https://www.devze.com 2023-01-02 14:46 出处:网络
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

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!

<Comb开发者_如何学CoBox
        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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号