我一直在尝试为WPF应用程序编写MVVM屏幕,使用async和await关键字为1编写异步方法.最初加载数据,2.刷新数据,3.保存更改然后刷新.虽然我有这个工作,但代码非常混乱,我不禁想到必须有更好的实现.任何人都可以建议更简单的实施?
这是我的ViewModel的简化版本:
public class ScenariosViewModel : BindableBase
{
public ScenariosViewModel()
{
SaveCommand = new DelegateCommand(async () => await SaveAsync());
RefreshCommand = new DelegateCommand(async () => await LoadDataAsync());
}
public async Task LoadDataAsync()
{
IsLoading = true; //synchronously set the busy indicator flag
await Task.Run(() => Scenarios = _service.AllScenarios())
.ContinueWith(t =>
{
IsLoading = false;
if (t.Exception != null)
{
throw t.Exception; //Allow exception to be caught on Application_UnhandledException
}
});
}
public ICommand SaveCommand { get; set; }
private async …Run Code Online (Sandbox Code Playgroud) 很抱歉,如果之前已经询问过,但谷歌几乎不可能.我认为int数组实现IEnumerable,因此Thing应该能够实现IThing.怎么没有?
public interface IThing
{
IEnumerable<int> Collection { get; }
}
public class Thing : IThing
{
public int[] Collection { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
注意
public class Thing : IThing
{
public int[] Array { get; set; }
public IEnumerable<int> Collection
{
get
{
return this.Array;
}
}
}
Run Code Online (Sandbox Code Playgroud)
很好.