我正在尝试绑定以与Xamarin Android中的AsyncLayoutInflater一起使用。
这是我的课程:创建视图,但没有任何绑定。关于我在做什么错的任何提示吗?
public static class MvxAsyncBindingExtensions
{
private static readonly AsyncLayoutInflater _inflater = new AsyncLayoutInflater(AndroidContext.CurrentTopActivity);
public static Task<View> BindingInflateAsync(this IMvxBindingContextOwner owner, int resourceId, ViewGroup viewGroup)
{
var context = (IMvxAndroidBindingContext)owner.BindingContext;
return context.BindingInflateAsync(resourceId, viewGroup);
}
public static Task<View> BindingInflateAsync(this IMvxAndroidBindingContext bindingContext, int resourceId, ViewGroup viewGroup)
{
var tcs = new TaskCompletionSource<View>();
var registration = new MvxBindingContextStackRegistration<IMvxAndroidBindingContext>(bindingContext);
var listener = new AsyncInflateFinishedListener(tcs, view => registration.Dispose());
_inflater.Inflate(resourceId, viewGroup, listener);
return tcs.Task;
}
private class AsyncInflateFinishedListener : Java.Lang.Object, AsyncLayoutInflater.IOnInflateFinishedListener
{
private readonly TaskCompletionSource<View> _tcs;
private readonly Action<View> _onCreated;
public AsyncInflateFinishedListener(TaskCompletionSource<View> tcs, Action<View> onCreated)
{
_tcs = tcs;
_onCreated = onCreated;
}
public void OnInflateFinished(View p0, int p1, ViewGroup p2)
{
_tcs.TrySetResult(p0);
_onCreated(p0);
}
}
}
然后我按如下方式使用它:
private async Task<View> CreateAndBindViewAsync(FilterItemEntity item)
{
var sourceBindingContext = this.BindingContext as MvxAndroidBindingContext;
var bindingContext = new MvxAndroidBindingContext(this.Context, sourceBindingContext.LayoutInflaterHolder);
var view = await bindingContext.BindingInflateAsync(_itemTemplateId, _flowLayout);
bindingContext.DataContext = item;
return view;
}
我有类似的代码可以正常使用BindingInflate
扩展名。
从this开始,我认为AsyncLayoutInflater.LayoutInflater应该使用context.LayoutInflater进行设置,但是LayoutInflater在AsyncLayoutInflater中是私有的,因此无法执行此操作。
但是您还有另一种选择。充气完成后,可以以编程方式进行绑定:
using (var bindingSet = this.CreateBindingSet<your_activity, your_view_model>())
{
bindingSet.Bind(view.TextView).To(vm => vm.Text);
bindingSet.Apply();
}