我正在尝试使用MVVM Light将数据绑定到网格。如果我执行以下操作,它将起作用:
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
}
现在,如果我将构造函数更改为以下代码,使用对Start
的异步调用,则网格不会获取数据:
public GuidePageViewModel(IChannelDataService channelDataService)
{
_channelDataService = channelDataService;
Start();
}
我知道这种异步问题,但我无法弄清楚。有人可以指出我做错了吗?
答案 0 :(得分:0)
首先,您不应该在constructor中调用异步方法。尝试更改逻辑,以便不需要该调用。
同时,请尝试检查AsyncMVVM。它包含一些有趣的模式,可以在异常的情况下检索数据,同时暴露通常的MVVM接口。