【问题标题】:How to bind MvxTableViewSource to dynamically created ViewModel with MvvmCross and Xamarin.iOS如何使用 MvvmCross 和 Xamarin.iOS 将 MvxTableViewSource 绑定到动态创建的 ViewModel
【发布时间】:2015-07-20 16:49:26
【问题描述】:

我已经创建了表源,并且不想将其绑定到当前数据上下文,而是绑定到另一个由 Controller 动态创建的 ViewModel。

//some button click

var context = new DynamicViewModel();
var source = new MyTableViewSource();
source.ItemsSource = context.DataItems; //I want this line to work with bindings

【问题讨论】:

  • 您是否尝试过在主视图模型中创建动态视图模型,然后使用它进行绑定? Set.Bind(source).For(ItemsSource).To(vm => vm.DynamicVM.Items)
  • 这是重构计划,因为现在那些动态视图模型是在视图代码中创建的,这可能是我的问题。

标签: ios mvvm data-binding xamarin mvvmcross


【解决方案1】:

在 View 方面,Mvx 绑定适用于 IMvxBindingContextOwner,而不是直接适用于 ViewModel - 这允许它们在整个 ViewModel 更改时进行更新。

因此,要执行您想做的事情,您需要提供一个 IMvxBindingContextOwner,它将您的动态视图模型作为当前 DataContext 保存在其 BindingContext 中。

为此,请尝试创建一个虚拟所有者,例如:

 public class MyOwner : IMvxBindingContextOwner 
 { 
     public MyOwner() { BindingContext = new MvxBindingContext(); {
     public IMvxBindingContext BindingContext { get; private set; } 
 } 

然后您应该能够将其用作新绑定集的目标 - 例如

 _owner = new MyOwner();
 _owner.BindingContext.DataContext = dynamicViewModel;
 var set = _owner.CreateBindingSet<MyOwner, DynamicViewModel>(); 
 // set.Bind statements
 set.Apply(); 

未测试...但应该可以工作...如果遇到问题,还可以考虑使用现成的MvxView 控件-它是BindingContextOwner,您可以设置它的DataContext

【讨论】:

  • 太棒了,这种方法让绑定非常灵活
猜你喜欢
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多