我有一个ObservableCollection
个对象存储在ViewModel
中,而且每个对象都要BoxView
添加到我的View
。我无法想象如何动态地实现这一点。我正在使用下面的代码,但是在绘制页面之前,OnBindingContextChanged()不会被调用。
如何为我的收藏中的每个成员绘制BoxViews
并显示它?
public partial class MyPage
{
private MyViewModel _viewModel;
public MyPage()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
_viewModel = BindingContext as MyViewModel;
var collection = _viewModel.MyCollection;
foreach (var item in cargoList)
{
BuildCargoItem(item.Width, item.Height, item.Position);
}
}
public void BuildCargoItem(int width = 150, int height = 150, int position = 0)
{
BoxView boxView = new BoxView
{
Color = Color.Blue,
WidthRequest = width,
HeightRequest = height,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
grid.Children.Add(boxView, 450, position);
}
}