In my current WPF project I was working without implementing INotifyPropertyChanged
in ViewModels however I ran into a problem where views' datagrids would load before the async functions finished getting the data which resulted in empty Datagrids. It's my first time using WPF and MVVM.
The View Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MLaRealERP.Models;
using System.ComponentModel;
namespace MLaRealERP.ViewModels
{
public class AlmacenesViewModel:INotifyPropertyChanged
{
public List<Almacen> insumos;
public AlmacenesViewModel()
{
insumos = new List<Almacen>();
}
public async void InitializeViewModel()
{
insumos = await Funciones.GetAll<Almacen>("Almacens",App.client);
}
}
}
The model
namespace MLaRealERP.Models
{
public class Almacen
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
}
}
The View
namespace MLaRealERP.Views
{
/// <summary>
/// Interaction logic for AlmacenesView.xaml
/// </summary>
public partial class AlmacenesView : Window
{
AlmacenesViewModel AlmacenesVM;
public AlmacenesView()
{
InitializeComponent();
AlmacenesVM = new AlmacenesViewModel();
AlmacenesVM.InitializeViewModel();
dgInsumos.ItemsSource = AlmacenesVM.insumos;
}
//public async void LoadViewItems()
//{
// insumos.InitializeViewModel();
//}
private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void btnAddInsumo_Click(object sender, RoutedEventArgs e)
{
dgInsumos.ItemsSource = AlmacenesVM.insumos;
}
private void btnVerInsumos_Click(object sender, RoutedEventArgs e)
{
}
}
}
The async http request function just in case its relevant
public static class Funciones
{
public static async Task<List<T>> GetAll<T>(string s, HttpClient client)
{
System.Threading.Tasks.Task<System.IO.Stream> streamTask;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
streamTask = client.GetStreamAsync(s);
var repositories = await JsonSerializer.DeserializeAsync<List<T>>(await streamTask);
return repositories;
}
public static async Task<T> Get<T>(string s, int i, HttpClient client)
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
s = s + "/" + i.ToString();
try
{
var item = await client.GetFromJsonAsync<T>(s);
return item;
}
catch { };
return default(T);
}
}