WPF组合框未显示"选定值"



我知道我是第无数个有同样问题的人,我在这个网站上检查了很多答案,但都没有解决我的问题。

我从数据网格中的一个组合框开始,它按预期工作。

<ComboBox ItemsSource="{Binding DataContext.ItemList,
RelativeSource={RelativeSource Mode=FindAncestor, 
AncestorType=DataGrid}}"
DisplayMemberPath="ItemName"                                   
SelectedValuePath="ItemID"
SelectedValue="{Binding ItemID, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cal:ActionMessage MethodName="AddRowCheck">
<cal:Parameter Value="{Binding ElementName=OrderList, Path=CurrentItem}"/>
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>

我对这个唯一的问题是,当我将Items添加到ItemList时,它们会显示在列表的底部,而不再按字母顺序显示。

为了解决这个问题,我更新了我的代码,如下

<Window.Resources>
<CollectionViewSource x:Key="sortedItemList" 
Source="{Binding ItemList}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ItemName" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources> 
.......
<ComboBox ItemsSource="{Binding Source={StaticResource sortedItemList}}"
DisplayMemberPath="ItemName"                                   
SelectedValuePath="ItemID"
SelectedValue="{Binding ItemID, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cal:ActionMessage MethodName="AddRowCheck">
<cal:Parameter Value="{Binding ElementName=OrderList, Path=CurrentItem}"/>
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox> 

现在项目按字母顺序排列,但所选项目不再显示。

我做错了什么?

我试图覆盖Item对象上的equal函数,以便它检查ID以查看两个项是否相等,但这并没有解决问题。

我自己找到了答案。错误发生在选择项目后触发的事件中。

AddRowCheck方法中,我向数据网格添加了一个新的空行,其中ComboBox指向相同的CollectionViewSource。

我不完全理解它背后的逻辑,但在用这个新信息检查这个网站后,我发现我必须设置

IsSynchronizedWithCurrentItem="False"

它奏效了。

最新更新