MVVM WPF Update combobox with databinding and EF core 6

candinho Silveira 1 Reputation point
2022-08-01T14:39:41.58+00:00

Hi everyone, i'n new to programing and i need some help with mvvm datagrid and updating the datagrid/combobox items source update after inserting data to the database:
public partial class NovaMedida : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(DescricaoNovaMedida))]
string descricaoN;

        [ObservableProperty]  
        [NotifyPropertyChangedFor(nameof(SiglaNovaMedida))]  
        string siglaN;  
  
        [ObservableProperty]  
        [NotifyPropertyChangedFor(nameof(ConvervorNovaMedida))]  
        decimal conversorN;  
        public string DescricaoNovaMedida => descricaoN;  
        public string SiglaNovaMedida => siglaN;  
        public double ConvervorNovaMedida => Convert.ToDouble(conversorN);  
        [RelayCommand]  
        void SalvarNovaMedida()  
        {  
            Medida medida = new Medida();  
            medida.Descricao = DescricaoNovaMedida;  
            medida.Sigla = SiglaNovaMedida;  
            medida.Conversor = Convert.ToDecimal(ConvervorNovaMedida);  
            using (var context = new AppDbContext())  
            {  
                context.Medida.Add(medida);  
                context.SaveChanges();  
                 
            }  
              
  
        }  
         
    }  

public class MedidasViewModel : ObservableObject
{
public ObservableCollection<Medida> _medidas;

    public ObservableCollection<Medida> Medidas  
    {  
        get { return _medidas; }  
        set { _medidas = value; }  
    }  

    public  MedidasViewModel()  
    {  
        _medidas = new ObservableCollection<Medida>();  

        using (AppDbContext context = new AppDbContext())  
        {  
            List<Medida> lista = context.Medida.ToList();  


            foreach (var item in lista)  
            {  
                _medidas.Add(item);  
                  
            }  
        }  
    }  
      
}  

And the binding to the cb:

<syncfusion:ComboBoxAdv x:Name="cmbMedida" FontSize="18"  Grid.Column="1" Grid.Row="4" MinWidth="300" Height="25"  ItemsSource="{Binding MedidasView.Medidas,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Sigla" SelectedValuePath="Sigla"  />  

And my problem, i can insert data to the db and when i open the window, my cb is filled, but when i add a new medida, my cb doen't update to contain the newly created medida, but if i close the window and open again, the cb get updated.

Developer technologies Windows Presentation Foundation
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.