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

查看:302
本文介绍了WPF:ComboBox with selecteditem set make not use of SelectedIndex = 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用SelectedItem绑定时,为什么我的组合框弹出式菜单中的第一个元素不显示在

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

相同的代码selecteditem + selectedindex是没有问题的!

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;

并且:

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

因为它应该真正工作。

推荐答案

这是因为 ItemsSource 集合与 SelectedItem 属性中的集合不同。我冒昧猜测,你使用一个对象上下文来查询 SchoolclassSubject 对象的列表 ItemsSource 绑定到,而是另一个上下文来查询绑定到 SelectedItem 的实际数据项。即使列表包含表示对象所持有的值的引用,它也不是真正相同的引用,而是相同数据的单独实例。

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.

方法来解决这个问题,大多数涉及使用 SelectedValuePath SelectedValue 而不是 SelectedItem 属性,但具体的解决方案将根据您的特定ORM而有所不同。

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.

这篇关于WPF:ComboBox with selecteditem set make not use of SelectedIndex = 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆