Assigning an async result to a data binding property

The following is an example implementation that uses the metro API and data binding (using MVVM) to populate the list of folders in the drop-down list.

The View model constructor uses the SetFolders (private async) method, which calls the expected fileService.GetFoldersAsync () method to get a list of folders. The folder list is then assigned to a property called "FoldersList". XAML uses this property to populate a drop-down list using data binding.

I wonder if there is a better way to set the FoldersList property without having to set it in the constructor, as shown below. I would prefer to call the GetFilesAsync method and set the value of the FileList property when the actual data binding occurs (not during class initialization). Since properties do not support async / await modifiers (as far as I know), I am trying to implement the correct solution. Any ideas were greatly appreciated.

The code is below.

ViewModel

public class FileViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private readonly IFileService fileService;

    public FileDataViewModel(IFileService fileService)
    {
        this.fileService = fileService;
        SetFolders();
    }

    private async void SetFolders ()
    {
        FoldersList = await fileService.GetFoldersAsync();
    }

    private IEnumerable< IStorageFolder > foldersList;
    public IEnumerable<StorageFolder> FoldersList
    {
        get { return foldersList; }
        private set
        {
            foldersList = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("FoldersList"));
            }
        }
    }
}

IFileService and implementation

public interface IFileService    {
    Task<IEnumerable<IStorageFolder>> GetFilesAsync();
  }

public class FileService : IFileService
{
    public async Task<IEnumerable<IStorageFolder>> GetFoldersAsync()
    {
        var folder = KnownFolders.DocumentsLibrary;
        return await folder.GetFoldersAsync();
    }
}
+5
source share
1 answer

ObservableCollection<T>, IEnumerable<T>. , . , , . , , .

IStorageFolder ViewModels.

private async Task LoadData()
{
   if(!IsLoading)
  {
    IsLoading = true;
     Folders = new ObservableCollection<Folder>(await fileService.GetFolderAsync());

  }
  IsLoading = false;
}

private ObservableCollection<Folder> _folders;

public  ObservableCollection<Folder> Folders
{
  get
  {
    if(_folders == null)
    {
      LoadData();//Don't await...
    }
    return _folders;

  }
  private set
  {
    SetProperty(ref _folders,value);
  }

}
private bool _isLoading;
public bool IsLoading
{
  get
  {
    return _isLoading;
  }
  private set
  {
    SetProperty(ref _isLoading,value);
  }
}

, IsLoading , , . , , . (_folders.Add, _folders.Remove, _folders.Clear...)

+6

All Articles