C# WPF组合框最初没有选择正确的项
我有一个WPF组合框,绑定到自定义对象列表,每个对象都包含一个IsSelected属性。此属性绑定到其相应ComboBoxItem的IsSelected属性。最初创建列表时,我将特定对象的IsSelected属性设置为true,期望在最初显示组合框时选择此项。但是,无论绑定列表中的哪个对象的IsSelected属性设置为true,组合框始终将列表中的第一项显示为选定项 我知道绑定工作正常,因为当我单击组合框并将其展开以显示所有可用选项时,组合框将更新以显示正确的选定项 这是定义我的组合框的XAML。它位于DataTemplate中,并从页面中动态添加/删除(如果相关):C# WPF组合框最初没有选择正确的项,c#,wpf,xaml,binding,combobox,C#,Wpf,Xaml,Binding,Combobox,我有一个WPF组合框,绑定到自定义对象列表,每个对象都包含一个IsSelected属性。此属性绑定到其相应ComboBoxItem的IsSelected属性。最初创建列表时,我将特定对象的IsSelected属性设置为true,期望在最初显示组合框时选择此项。但是,无论绑定列表中的哪个对象的IsSelected属性设置为true,组合框始终将列表中的第一项显示为选定项 我知道绑定工作正常,因为当我单击组合框并将其展开以显示所有可用选项时,组合框将更新以显示正确的选定项 这是定义我的组合框的XAM
<ComboBox ItemsSource="{Binding DataContext.YearList, RelativeSource={RelativeSource AncestorType=Window}}" IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ComboBox.ItemContainerStyle>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Object}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
尝试删除IsSynchronizedWithCurrentItem=True。该设置告诉控件使用绑定集合生成的ICollectionView上的CurrentItem,该视图默认为列表中的第一项。如果您想查看其功能,可以使用CollectionViewSource.GetDefaultViewYearList在代码中使用此视图,然后查看或更改当前项。尝试绑定到SelectedItem属性,ComboBox默认情况下不会选择第一项,但会选择数据绑定的源:
<ComboBox ItemsSource="{Binding YearList, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem="{Binding <YourDefinedSelectedItemProperty>, RelativeSource={RelativeSource AncestorType=Window}}">
希望这能有所帮助。感谢您的回复,但是将IsSynchronizedWithCurrentItem设置为false会导致组合框中最初显示未选择任何项目,该组合框为空。