I have 2 DataGrid
's on a window, when you click a row in the top DataGrid
it calls the CurrentChanged event to get data for the bottom DataGrid
to show models for that car brand. The UI gets blocked when clicking a row because the method takes a while to finish. How do I get async await to work so the UI doesn't get blocked?
public class MainWindowViewModel
{
private ObservableCollection<Company> carCollectionOC = new ObservableCollection<Company>();
private ObservableCollection<Vehicle> vehicleOC = new ObservableCollection<Vehicle>();
private VehicleService vehicleService;
public ICollectionView CarCollection { get; set; }
public ICollectionView VehicleCollection { get; set; }
public MainWindowViewModel()
{
this.carCollectionOC.Add(new Company() { Brand = "Ford", Established = 1903 });
this.carCollectionOC.Add(new Company() { Brand = "Vauxhall", Established = 1857 });
this.CarCollection = new ListCollectionView(this.carCollectionOC);
this.CarCollection.CurrentChanged += CarCollection_CurrentChanged;
this.vehicleService = new VehicleService();
this.VehicleCollection = new ListCollectionView(this.vehicleOC);
}
private async void CarCollection_CurrentChanged(object sender, EventArgs e)
{
Company company = (Company)(sender as ICollectionView).CurrentItem;
this.vehicleOC = await this.GetVehiclesAsync(company.Brand);
}
private async Task<ObservableCollection<Vehicle>> GetVehiclesAsync(string carBrand)
{
this.vehicleOC.Clear();
foreach (var item in await this.vehicleService.GetVehicleListAsync(carBrand))
this.vehicleOC.Add(item);
Console.WriteLine("finishing GetVehiclesAsync");
return this.vehicleOC;
}
}
The GetVehicleListAsync is:
public Task<List<Vehicle>> GetVehicleListAsync(string carBrand)
{
for (var i = 600000000; i >= 0; i--)
{
// simulate a long process
}
return Task.FromResult(this.vehicleList.Where(item => item.Brand == carBrand).ToList());
}