如何使用 MvvmCross 和 Xamarin.iOS 将 MvxTableViewSource 绑定到动态创建的 ViewModel
How to bind MvxTableViewSource to dynamically created ViewModel with MvvmCross and Xamarin.iOS
我已经创建了 table 源并且不想将它绑定到当前数据上下文,而是绑定到另一个由 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
在视图方面,Mvx 绑定适用于 IMvxBindingContextOwner
而不是直接适用于 ViewModel
- 这允许它们在整个 ViewModel 更改时更新。
因此,要执行您想做的事情,您需要提供一个 IMvxBindingContextOwner
将您的动态视图模型作为其 BindingContext 中的当前 DataContext。
为此,请尝试创建一个虚拟所有者,例如:
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
我已经创建了 table 源并且不想将它绑定到当前数据上下文,而是绑定到另一个由 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
在视图方面,Mvx 绑定适用于 IMvxBindingContextOwner
而不是直接适用于 ViewModel
- 这允许它们在整个 ViewModel 更改时更新。
因此,要执行您想做的事情,您需要提供一个 IMvxBindingContextOwner
将您的动态视图模型作为其 BindingContext 中的当前 DataContext。
为此,请尝试创建一个虚拟所有者,例如:
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