Search code examples
wpfdatagriddatagridcomboboxcolumn

wpf datagrid combo box binding to database


I want my DataGrid have ComboBox with default value for example I have a column for Genre:

  1. Action
  2. Drama
  3. Comedy

I Want ComboBox Show those data and then select the item in database (for example in database Genre is Drama.

  1. I use WPF Net 6 with EF Sqlite for manage Database.

  2. in Database Class I set Genre as string.

  3. DataGrid of other Column I use Something like this:

     <DataGridTextColumn Header="ID" Binding="{Binding Path=ID,UpdateSourceTrigger=PropertyChanged}"/>
    
  4. in Code Behind: DgTest.ItemsSource=db.Test.ToList();


Solution

  • This is how i fix my problem. same as Firo but in simple way.

    My Model for Genre:

    public int ID {get; set;}
    public string? Title {get; set;}
    

    my Repository:

    Create A list of Genre and then Return it
    

    My View-Model

    public ObservableCollection<Genre> AllGenreList => new (_repository.GetAllGenre())
    private Genre _genre;
    public Genre SelectedGenre{get=> _genre; set{ _genre=value; ONotifyPropertyChanged(nameof(Genre);}
    

    and then Bind AllGenreList to ComboBox.

    <ComboBox ItemsSource="{Binding AllGenreList }" SelectedItem="{Binding SelectedGenre}"/>
    

    this is how i fix my problem. hope solve some one else problem.