Search code examples
mvvmxamarin.formsstacklayout

Adding Children in StackLayout using Binding in ViewModel, Xamarin.Forms


I am trying to implement MVVM in my Xamarin.Forms project.

This is my StackLayout with x:Name

<StackLayout x:Name="approvalsStack"></StackLayout>

And This is how I am populating Children in this StackLayout

StackLayout stack = new StackLayout();
                    Frame frame = new Frame { BorderColor = Color.LightGray };
                    frame.Content = new Label { Text = a.FullName + " (" + a.Decision + ")" + " " + a.DecisionDate.ToString() };
                    stack.Children.Add(frame);
                    approvalsStack.Children.Add(stack);

Now I am stuck, How can I populate the children using ViewModel/Binding.


Solution

  • You can't do it in that way, as you can see here, Property Children in StackLayout is not a Bindable property.

    However you can solve that by making custom one with implementation of bindable-property which will have some ItemSource for dynamically adding/removing items from it, or you can just use some great community implementations of RepeaterView for Xamarin.Forms, which I recommend you to do.

    RepeaterView is basically a Bindable StackLayout where you can populate items dynamically.

    I recommend you to take a look at this one here from Glenn Versweyveld, if you want you can search on google or on github for some more additional ones (but I strongly recommend you this one).

    Wishing you lots of luck with coding!