当我在定义中继命令处理程序的 lambda 语句中使用数据服务的注入实例时,该处理程序永远不会被调用(它与按钮相关联)。当我在 lambda 中声明数据服务的实例时,它工作正常。有任何想法吗?
编辑:创建类变量 _dataService 并在视图模型构造函数中对其进行初始化。在中继命令处理程序中使用类变量,一切正常。
private IDataService _dataService;
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
Batches = new ObservableCollection<Batch>();
#region RefreshCommand
RefreshCommand = new RelayCommand(
() =>
{
var t1 = Task<ObservableCollection<Batch>>.Factory.StartNew(() =>
{
// WHEN I UNCOMMENT AND COMMENT OUT BELOW, WORKS FINE.
//DataService test = new DataService();
//ObservableCollection<Batch> batches = test.GetBatchesToProcess();
//
// THIS NOW WORKS.
return _dataService.GetBatchesToProcess();
});
try
{
t1.Wait();
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
if (e is SqlException)
{
MessageBox.Show("Sql Exception: " + e.Message);
}
else
{
MessageBox.Show("Unexpected error: " + e.Message);
}
}
return;
}
Batches = t1.Result;
}
);
#endregion
}