C# 将第一项设置为WPF组合框中的选定项
我试图在默认情况下将组合框中的第一项设置为所选项。但以下代码不起作用:C# 将第一项设置为WPF组合框中的选定项,c#,wpf,xaml,combobox,C#,Wpf,Xaml,Combobox,我试图在默认情况下将组合框中的第一项设置为所选项。但以下代码不起作用: <ComboBox HorizontalAlignment="Left" x:Name="cbxPrograms" Grid.Column="2" Grid.Row="1" VerticalAlignment="Top" Width="270" Height="28" IsSynchronizedWithCurrentItem="True" SelectedIndex="0"
<ComboBox HorizontalAlignment="Left" x:Name="cbxPrograms" Grid.Column="2" Grid.Row="1"
VerticalAlignment="Top" Width="270" Height="28" IsSynchronizedWithCurrentItem="True"
SelectedIndex="0"
ItemsSource= "{Binding Path=ProgramCodeSource, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"
SelectedItem="{Binding ProgramCode, Mode=TwoWay}">
尝试使用SelectedValue=“{Binding ProgramCode,Mode=TwoWay}”我不知道您的视图模型是什么样子,但您的SelectedItem需要设置为列表中类型的实例
<ComboBox
HorizontalAlignment="Left"
x:Name="cbxPrograms"
Grid.Column="2"
Grid.Row="1"
VerticalAlignment="Top"
Width="270"
Height="28"
SelectedIndex="0"
IsSynchronizedWithCurrentItem="True"
ItemsSource= "
{Binding Path=EntityCollectionSource,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"
SelectedItem="{Binding Entity,Mode=TwoWay}">
如果您有一个名为
ProgramCodeSource
的集合属性和一个名为ProgramCode
的属性,该属性的类型与集合中的项相同…:
<ComboBox ItemsSource="{Binding ProgramCodeSource}"
SelectedItem="{Binding ProgramCode, Mode=TwoWay}" ... />
您可以在初始化数据后执行此操作:
ProgramCodeSource = new ObservableCollection<YourDataType>(GetData());
ProgramCode = ProgramCodeSource.FirstOrDefault();
ProgramCodeSource=新的ObservableCollection(GetData());
ProgramCode=ProgramCodeSource.FirstOrDefault();
使用
FirstOrDefault
方法很好,因为如果GetData()
方法不返回任何内容,则不会出现错误。我尝试使用所选值,但是默认情况下未选择第一项。SelectedItem中的绑定不应该是ProgramCodeSource而不是ProgramCode吗?请查看此页可能是一个愚蠢的问题,但您正在将ProgramCode设置为绑定之前ProgramCodeSource集合中的第一个对象,或者在绑定之后设置时引发属性更改?
ProgramCodeSource = new ObservableCollection<YourDataType>(GetData());
ProgramCode = ProgramCodeSource.FirstOrDefault();