Xamarin Android 与 MVVMLight︰ 只有原始线程创建 view 层次结构可 touch 其意见

标签: Android C#
发布时间: 2017/3/4 6:24:52
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我得到这个错误每次更新 ViewModel property 已经绑定在 activity 。我知道这个错误从另一个线程 (而不是 UI 线程) 与更新 UI 相关但我不能控制 MVVMLight 如何绑定...

activity:

private readonly List<Binding> _bindings = new List<Binding>();

public PersonViewModel ViewModel
{
    get
    {
        return App.Locator.Detail;
    }
}

private TextView _txtName;
public TextView TxtName
{
    get
    {
        return _txtName ??
            (_txtName = FindViewById<TextView>(Resource.Id.txtName));
    }
}

protected async override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.Detail);

    _bindings.Add(this.SetBinding(
        () => ViewModel.Person.Name,
        () => TxtName.Text));

    await Task.Factory.StartNew(() => { ViewModel.LoadDetailCommand.Execute(null); });
}

视图模型︰

private IDataService _dataService;

private PersonObj _person; 
public PersonObj Person
{
    get
    {
        return _person;
    }
    set
    {
        Set(ref _person, value);
    }
}

private RelayCommand _loadDetailCommand;
public RelayCommand LoadDetailCommand
{
    get
    {
        return _loadDetailCommand
               ?? (_loadDetailCommand = new RelayCommand(
                   async () =>
                   {
                       await LoadDataAsync();
                   }));
    }
}

public PersonViewModel(IDataService dataService)
{
    _dataService = dataService;
}

private async Task LoadDataAsync()
{
    try
    {
        Person= await _dataService.GetPerson(0);
    }
    catch (Exception ex)
    {
        // Exception here!!
    }
}

解决方法 1:

好吧,我管理它创建任务在 ViewModel 必要时和等待它,所以我可以捕获所有主控的异常︰

Person = await Task.Run(async () =>
{
    var p = await _dataService.GetPerson(0);
    return p;
});

感谢 @xleon 的帮助。

赞助商