动态添加BoxViews

时间:2018-02-12 17:50:44

标签: c# xamarin xamarin.forms

我有一个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);
    }
}

0 个答案:

没有答案