Hi @Tom Meier , Welcome to Microsoft Q&A,
In C#, you cannot directly call an asynchronous method from a constructor. Constructors do not support the await
keyword, which is required to run asynchronous code properly.
A readonly
field can only be assigned during the declaration or in a constructor. Since you are trying to assign _reservations
in an asynchronous method (InitializeAsync
), this violates the readonly
constraint.
public class ReservationListingViewModel : ViewModelBase
{
private ObservableCollection<ReservationViewModel> _reservations;
public IEnumerable<ReservationViewModel> Reservations => _reservations;
public ReservationListingViewModel()
{
// Initialize asynchronously
InitializeAsync().ConfigureAwait(false);
}
private async Task InitializeAsync()
{
_reservations = await GetReservations();
}
public async Task<ObservableCollection<ReservationViewModel>> GetReservations()
{
var reservations = new ObservableCollection<ReservationViewModel>();
for (int i = 0; i < 1000; i++)
{
reservations.Add(new ReservationViewModel(new Reservation("1,2", "Ron" + i, DateTime.Now, DateTime.Now)));
}
return reservations;
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.