简体   繁体   中英

Async Binding Issues with MVVM Light

I am trying to bind data to a grid using MVVM Light. If I do the following it works:

public class GuidePageViewModel : ViewModelBase
{
    private ObservableCollection<SimpleChannelData> _simpleChannelDataList;
    private IChannelDataService _channelDataService;

    public GuidePageViewModel(IChannelDataService channelDataService)
    {
        _channelDataService = channelDataService;

        ATest(); // Create data synchronously here
    }

    private void ATest()
    {
        SimpleChannelDataList = new ObservableCollection<SimpleChannelData>();

        var record = new SimpleChannelData()
        {
            Cn = 120,
            Csign = "Hey",
            Hd = "Y",
            Index = 1,
            Premium = "y",
            TrbId = 9
        };

        SimpleChannelDataList.Add(record);
    }

    private async void Start()
    {
        await LoadChannelData();
    }

    private async Task LoadChannelData()
    {
        SimpleChannelDataList = new ObservableCollection<SimpleChannelData>((await _channelDataService.GetChannelData()));
        RaisePropertyChanged(() => SimpleChannelDataList);
    }

    #region Public Properties

    public ObservableCollection<SimpleChannelData> SimpleChannelDataList
    {
        get
        {
            return _simpleChannelDataList;
        }
        set
        {
            if (Set(() => SimpleChannelDataList, ref  _simpleChannelDataList, value))
            {
                RaisePropertyChanged(() => SimpleChannelDataList);
            }

        }
    }
    #endregion
}

Now, if I change the constructor to the following instead, using an asynchronous call to Start , the grid does not get the data:

public GuidePageViewModel(IChannelDataService channelDataService)
{
    _channelDataService = channelDataService;
    Start();
}

I know this some sort of Async issue, but I cannot figure it out. Can someone point out what I am doing wrong?

At first, you should not call async methods in the constructor . Try to change your logic so that that call is not required.

In mean time, try to check AsyncMVVM . It contains some interesting patterns to retrieve in an async way the data while exposing the usual MVVM interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM