C#WPF Combobox选择第一项

Rob*_*ter 21 c# wpf xaml combobox dataset

美好的一天,

我希望我的组合框能够选择其中的第一项.我正在使用C#和WPF.我从DataSet中读取数据.填充组合框:

DataTable sitesTable = clGast.SelectAll().Tables[0];
cbGastid.ItemsSource = sitesTable.DefaultView;
Run Code Online (Sandbox Code Playgroud)

组合框XAML代码:

<ComboBox 
   Name="cbGastid" 
   ItemsSource="{Binding}" 
   DisplayMemberPath="Description" 
   SelectedItem="{Binding Path=id}"
   IsSynchronizedWithCurrentItem="True" />
Run Code Online (Sandbox Code Playgroud)

如果我尝试:

cbGastid.SelectedIndex = 0; 
Run Code Online (Sandbox Code Playgroud)

它不起作用.

Bri*_*ian 37

XAML用这个更新你的:

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />  // Add me!
Run Code Online (Sandbox Code Playgroud)

  • 属性`IsSynchronizedWithCurrentItem ="True"`对我有用 (13认同)
  • 我的`SelectedIndex ="0"`仍然会产生一个空的组合,当你把它放下时,项目在顶部为零. (8认同)
  • 谢谢!:) IsSynchronizedWithCurrentItem为我做了诀窍! (3认同)
  • IsSynchronizedWithCurrentItem="True" 就足够了,不需要 SelectedIndex="0"。 (3认同)

123*_*9 0 7

试试这个,而不是SelectedIndex

cbGastid.SelectedItem = sitesTable.DefaultView.[0][0]; // Assuming you have items here.
Run Code Online (Sandbox Code Playgroud)

或者在Xaml中设置它

<ComboBox 
        Name="cbGastid" 
        ItemsSource="{Binding}" 
        DisplayMemberPath="Description" 
        SelectedItem="{Binding Path=id}"
        IsSynchronizedWithCurrentItem="True"
        SelectedIndex="0" />
Run Code Online (Sandbox Code Playgroud)