Good afternoon, there is a Class with properties and sampling:

public partial class Register : Window { public int Id { get; set; } public string Name { get; set; } public ObservableCollection<Roles> ItemsForRoles { get; set; } public Register() { DbModelContainer db = new DbModelContainer(); ObservableCollection<Roles> ItemsForRoles = new ObservableCollection<Roles>(); var query = db.RolesSet.ToList(); foreach (var roles in query) { ItemsForRoles.Add( new Roles { Id = roles.Id, Name = roles.Name } ); } } } 

And ComboBox:

 <ComboBox Name="role" ItemsSource="{Binding ItemsForRoles}"> <ComboBoxItem Content="{Binding Name}"></ComboBoxItem> </ComboBox> 

Tell me, please, how in the XAML code to correctly bind the data to the ComboBox, so that all entries are displayed, not just one. It is necessary to remove from the database the entries in this ComboBox and the passed parameter to make Id, not Name.

Resolving a question from recent comments (setting IsEnabled = false to the first (selected) item):

 <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Style.Triggers> <DataTrigger Binding="{Binding Id}" Value="-1"> <Setter Property="IsEnabled" Value="False"/> </DataTrigger> </Style.Triggers> </Style> </ComboBox.ItemContainerStyle> 
  • And why do you set the ComboBoxItem separately if you already have items in the ItemsSource? - user2455111

1 answer 1

You only need the ItemsSource property for your Combobox

 <ComboBox Name="role" ItemsSource="{Binding ItemsForRoles}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding Path=Id}"> </ComboBox> 

what you separately set ComboBoxItem scrubs your ItemsSource list

  • Nothing derives - Dmitriy
  • Everything corrected, it was necessary to add this.DataContext = this to the Loaded window; - Dmitriy
  • Thank. Only for some reason, when choosing, he began to highlight the combo box with a red frame in the application, although the neighboring one does not do this :) - Dmitry
  • @ Dmitry probably doesn’t see any of the parameters DisplayMemberPath = "Name" SelectedValuePath = "Name" SelectedValue = "{Binding Path = Id}" - user2455111
  • @ Dmitry I will try to create a test case and test it - user2455111