jose silveira

jose silveira

  • 2.1k
  • 5
  • 252

Wpf databinding collection update after insert using Entity Framework

Jul 30 2022 12:03 AM

Hi everyone, i'n learning c#, currently using wpf and databinding, i've created the models and view model:

 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);

                }
            }
        }
        
    }
<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"  />

When i load the window, it get all the data, but when i add a new medida into the database, my combobox doesn't update.

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();
               
            }
            

        }
       
    }

I've googled for days i coun't find a solution


Answers (2)